【发布时间】:2020-04-06 11:26:55
【问题描述】:
我正在尝试找到一种方法来获取 Python 3.6+ 的下一个键(已订购)
例如:
dict = {'one':'value 1','two':'value 2','three':'value 3'}
我想要实现的是返回下一个键的功能。类似:
next_key(dict, current_key='two') # -> should return 'three'
这是我目前所拥有的:
def next_key(dict,key):
key_iter = iter(dict) # create iterator with keys
while k := next(key_iter): #(not sure if this is a valid way to iterate over an iterator)
if k == key:
#key found! return next key
try: #added this to handle when key is the last key of the list
return(next(key_iter))
except:
return False
return False
嗯,这是基本的想法,我想我很接近,但是这段代码给出了一个 StopIteration 错误。请帮忙。
谢谢!
【问题讨论】:
-
为什么不直接使用
iteritems()?next是什么意思?如果遍历所有键,使用内置的keys(),为什么还不够? -
你可以做到这一点,但这真的很尴尬(不是对 dicts 的快速操作,dicts 保留顺序但本身没有排序 - 少于
OrderedDicts,反正)。是否有一个问题被删除了,您可以提出更好的解决方案? -
@F.A 如果你已经找到答案,我建议你把这个问题记下来。有多个相同的问题没有意义。
-
@MayankPorwal 人们什么时候才能停止声称字典仍然是无序的?
标签: python dictionary iterator python-3.8