【问题标题】:Return next key of a given dictionary key, python 3.6+返回给定字典键的下一个键,python 3.6+
【发布时间】: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,反正)。是否有一个问题被删除了,您可以提出更好的解决方案?
  • 这能回答你的问题吗? How to get the "next" item in an OrderedDict?
  • @F.A 如果你已经找到答案,我建议你把这个问题记下来。有多个相同的问题没有意义。
  • @MayankPorwal 人们什么时候才能停止声称字典仍然是无序的?

标签: python dictionary iterator python-3.8


【解决方案1】:

循环 while k := next(key_iter) 没有正确停止。使用iter 手动迭代可以通过捕获StopIteration 来完成:

iterator = iter(some_iterable)

while True:
    try:
        value = next(iterator)
    except StopIteration:
        # no more items

或通过将默认值传递给next 并让它为您捕获StopIteration,然后检查该默认值(但您需要选择一个不会出现在您的可迭代对象中的默认值!):

iterator = iter(some_iterable)

while (value := next(iterator, None)) is not None:
    # …

# no more items

但迭代器本身是可迭代的,因此您可以跳过所有这些并使用普通的 ol' for 循环:

iterator = iter(some_iterable)

for value in iterator:
    # …

# no more items

翻译成你的例子:

def next_key(d, key):
    key_iter = iter(d)

    for k in key_iter:
        if k == key:
            return next(key_iter, None)

    return None

【讨论】:

  • 非常感谢您的回答!我从阅读中学到了很多东西。您会说您提出的解决方案比@heapoverflow 提出的解决方案更好吗?你提到了一些关于使用“in”的副作用,我不确定你的意思。我喜欢他的解决方案,因为它避免了 for 循环,所以它更短
  • @F.A:我想说最好的解决方案可能是根本不涉及此功能的解决方案:] 就像我评论的那样,使用dict 是一件很奇怪的事情,所以我认为你应该看看你试图解决的问题(并随时在这里询问这个问题!另见:meta.stackexchange.com/questions/66377/what-is-the-xy-problem)。至于in:大多数人看到都会很惊讶,但是当它的意图很明确时,它在一个小函数中的方式并不算太糟糕。
【解决方案2】:

一种迭代方式...

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

【讨论】:

  • 哇。这很糟糕,但也很漂亮。
  • @Ry- 你的意思是因为复杂而可怕吗? (如果 dict 就是我们所拥有的,我怀疑它是否可以改进。)
  • 不,使用in 的副作用:D
  • @Ry- 啊。呵呵:-)。我喜欢这样做。 Here's 另一个最近的。
  • @F.A 它没有明确涵盖where it should be,但我相信它与“未定义__contains__()但定义__iter__()的用户定义类”属于同一类别,所以它消耗迭代器直到找到值(或者直到最后,如果它不在那里)。
【解决方案3】:

您可以将字典的键作为列表获取,并使用index() 获取下一个键。您还可以使用try/except 块检查IndexError

my_dict = {'one':'value 1','two':'value 2','three':'value 3'}

def next_key(d, key):
  dict_keys = list(d.keys())
  try:
    return dict_keys[dict_keys.index(key) + 1]
  except IndexError:
    print('Item index does not exist')
    return -1

nk = next_key(my_dict, key="two")
print(nk)

而且你最好不要使用dictlist 等作为变量名。

【讨论】:

    【解决方案4】:
    # Python3 code to demonstrate working of 
    # Getting next key in dictionary Using list() + index()
    
    # initializing dictionary 
    test_dict = {'one':'value 1','two':'value 2','three':'value 3'}
    
    def get_next_key(dic, current_key):
        """ get the next key of a dictionary.
    
        Parameters
        ----------
        dic: dict
        current_key: string
    
        Return
        ------
        next_key: string, represent the next key in dictionary.
        or
        False If the value passed in current_key can not be found in the dictionary keys,
        or it is last key in the dictionary
        """
    
        l=list(dic) # convert the dict keys to a list
    
        try:
            next_key=l[l.index(current_key) + 1] # using index method to get next key
        except (ValueError, IndexError):
            return False
        return next_key
    

    get_next_key(test_dict, 'two')

    '三'

    get_next_key(test_dict, '三')

    错误

    get_next_key(test_dict, 'one')

    '两个'

    get_next_key(test_dict, '不存在')

    错误

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-31
      • 2022-12-06
      • 1970-01-01
      • 2013-08-07
      • 2017-08-31
      • 1970-01-01
      • 2021-07-26
      • 1970-01-01
      相关资源
      最近更新 更多