小编F. *_*. A的帖子

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

我正在尝试找到一种方法来获取 Python 3.6+ 的下一个密钥(已排序)

例如:

dict = {'one':'value 1','two':'value 2','three':'value 3'}
Run Code Online (Sandbox Code Playgroud)

我想要实现的是返回下一个键的功能。就像是:

next_key(dict, current_key='two')   # -> should return 'three' 
Run Code Online (Sandbox Code Playgroud)

这是我到目前为止所拥有的:

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

Run Code Online (Sandbox Code Playgroud)

好吧,这就是基本思想,我想我已经很接近了,但是这段代码给出了 StopIteration 错误。请帮忙。

谢谢你!

python dictionary iterator python-3.8

2
推荐指数
2
解决办法
3885
查看次数

标签 统计

dictionary ×1

iterator ×1

python ×1

python-3.8 ×1