[英]Return next key of a given dictionary key, python 3.6+
I am trying to find a way to get the next key of a Python 3.6+ (which are ordered)我正在尝试找到一种方法来获取 Python 3.6+ 的下一个密钥(已订购)
For example:例如:
dict = {'one':'value 1','two':'value 2','three':'value 3'}
What I am trying to achieve is a function to return the next key.我想要实现的是 function 返回下一个密钥。 something like:就像是:
next_key(dict, current_key='two') # -> should return 'three'
This is what I have so far:这是我到目前为止所拥有的:
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
well, that is the basic idea, I think I am close, but this code gives a StopIteration error.好吧,这是基本思想,我想我很接近,但是这段代码给出了 StopIteration 错误。 Please help.请帮忙。
Thank you!谢谢!
An iterator way...一种迭代方式...
def next_key(dict, key):
keys = iter(dict)
key in keys
return next(keys, False)
Demo:演示:
>>> next_key(dict, 'two')
'three'
>>> next_key(dict, 'three')
False
>>> next_key(dict, 'four')
False
Looping while k:= next(key_iter)
doesn't stop correctly. while k:= next(key_iter)
没有正确停止时循环。 Iterating manually with iter
is done either by catching StopIteration
:使用iter
手动迭代可以通过捕获StopIteration
来完成:
iterator = iter(some_iterable)
while True:
try:
value = next(iterator)
except StopIteration:
# no more items
or by passing a default value to next
and letting it catch StopIteration
for you, then checking for that default value (but you need to pick a default value that won't appear in your iterable:):或者通过将默认值传递给next
并让它为您捕获StopIteration
,然后检查该默认值(但您需要选择一个不会出现在您的可迭代对象中的默认值:):
iterator = iter(some_iterable)
while (value := next(iterator, None)) is not None:
# …
# no more items
but iterators are, themselves, iterable, so you can skip all that and use a plain ol' for loop:但是迭代器本身是可迭代的,因此您可以跳过所有这些并使用普通的 ol' for 循环:
iterator = iter(some_iterable)
for value in iterator:
# …
# no more items
which translates into your example as:这转化为您的示例:
def next_key(d, key):
key_iter = iter(d)
for k in key_iter:
if k == key:
return next(key_iter, None)
return None
You can get the keys of the dictionary as list and use index()
to get the next key.您可以将字典的键作为列表获取,并使用index()
获取下一个键。 You can also check for IndexError
with try/except
block:您还可以使用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)
And you better not use dict
, list
etc as variable names.你最好不要使用dict
、 list
等作为变量名。
# 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, '两个')
'three' '三'
get_next_key(test_dict, 'three') get_next_key(test_dict, '三')
False错误的
get_next_key(test_dict, 'one') get_next_key(test_dict, '一个')
'two' '二'
get_next_key(test_dict, 'NOT EXISTS') get_next_key(test_dict, '不存在')
False错误的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.