[英]Store the value of a key-value by its order?
阅读数据结构并有一个问题。 这是一本字典:
example = {'the': 8,
'metal': 8,
'is': 23,
'worth': 3,
'many': 3,
'dollars': 2,
'right': 2}
如何按顺序将键/值对的值存储到变量中?
例如,如何存储第三对的值,即 23?
试过这个,这是不正确的:
for k in example:
if k == 3:
a_var = example(k)
如果您知道键/值已按正确顺序插入,则可以使用islice()
获取第三个键/值对。 这样做的好处是不需要创建完整的值列表,并且比显式编写循环要简单一些:
from itertools import islice
example = {
'the': 8,
'metal': 8,
'is': 23,
'worth': 3,
'many': 3,
'dollars': 2,
'right': 2
}
key, val = next(islice(example.items(), 2, None))
# 'is', 23
这可以满足您的需要:
example = {'the': 8,
'metal': 8,
'is': 23,
'worth': 3,
'many': 3,
'dollars': 2,
'right': 2}
k=0
for key in example:
k+=1
if k == 3:
a_var = example[key]
print(a_var)
Output:
23
如果你真的认为你需要这个:
def find( example, ordinal):
for k,value in enumerate(example.values()):
if k == ordinal:
return value
或者
def find( example, ordinal):
return list(example.values())[ordinal]
您只能通过字典的键确定第三对值:
a_var = example['is']
您应该遍历键,然后如果键 3 的值您应该将其保存到变量:
for key in example:
if example[key] == 23:
a_var = example[key]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.