Вернуть следующий ключ данного словарного ключа, python 3.6+ - PullRequest
0 голосов
/ 06 апреля 2020

Я пытаюсь найти способ получить следующий ключ 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

ну, это базовая идея c, я думаю, что я близок, но этот код дает ошибка StopItate. Пожалуйста помоги.

Спасибо!

Ответы [ 4 ]

3 голосов
/ 06 апреля 2020

Способ итератора ...

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
3 голосов
/ 06 апреля 2020

Цикл 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 для l oop:

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
1 голос
/ 06 апреля 2020

Вы можете получить ключи словаря в виде списка и использовать index(), чтобы получить следующий ключ. Вы также можете проверить IndexError с try/except блоком:

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)

И вам лучше не использовать dict, list et c в качестве имен переменных.

0 голосов
/ 06 апреля 2020
# 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')

'three'

get_next_key (test_dict, 'three')

False

get_next_key (test_dict, 'one')

'two'

get_next_key (test_dict, 'NOT EXISTS ')

False

...