簡體   English   中英

返回給定字典鍵的下一個鍵,python 3.6+

[英]Return next key of a given dictionary key, python 3.6+

我正在嘗試找到一種方法來獲取 Python 3.6+ 的下一個密鑰(已訂購)

例如:

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

我想要實現的是 function 返回下一個密鑰。 就像是:

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

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

您可以將字典的鍵作為列表獲取,並使用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等作為變量名。

# 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, '兩個')

'三'

get_next_key(test_dict, '三')

錯誤的

get_next_key(test_dict, '一個')

'二'

get_next_key(test_dict, '不存在')

錯誤的

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM