gpt4 book ai didi

python - 返回给定字典键的下一个键,python 3.6+

转载 作者:行者123 更新时间:2023-12-05 08:18:34 25 4
gpt4 key购买 nike

我正在尝试找到一种方法来获取 Python 3.6+ 的下一个 key (已订购)

例如:

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 错误。请帮忙。

谢谢!

最佳答案

迭代器方式...

def next_key(dict, key):
keys = iter(dict)
key in keys
return next(keys, False)

演示:

>>> next_key(dict, 'two')
'three'
>>> next_key(dict, 'three')
False
>>> next_key(dict, 'four')
False

关于python - 返回给定字典键的下一个键,python 3.6+,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61058709/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com