Return 给定字典键的下一个键,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'}
我想要实现的是 return 下一个键的功能。类似于:
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 错误。请帮忙。
谢谢!
您可以将字典的键作为列表获取,并使用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)
最好不要使用 dict
、list
等作为变量名。
迭代器方式...
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
# 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')
错
get_next_key(test_dict, 'one')
'two'
get_next_key(test_dict, 'NOT EXISTS')
错
我正在尝试找到一种方法来获取 Python 3.6+(已订购)的下一个密钥
例如:
dict = {'one':'value 1','two':'value 2','three':'value 3'}
我想要实现的是 return 下一个键的功能。类似于:
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 错误。请帮忙。
谢谢!
您可以将字典的键作为列表获取,并使用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)
最好不要使用 dict
、list
等作为变量名。
迭代器方式...
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
# 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')
错
get_next_key(test_dict, 'one')
'two'
get_next_key(test_dict, 'NOT EXISTS')
错