首页 > 解决方案 > 如何使用我要获取的字典的一个键/值对从字典列表中访问字典

问题描述

我有一个字典列表,它们都有相同的键。我有一个键的特定值,并且想要访问/打印包含该特定值的字典。除了循环整个列表,检查键的相应值并使用 if 语句将其打印出来之外,我想不出任何办法,也就是说,如果给定的值与键匹配。

for enrollment in enrollments:
    if enrollment['account_key'] == a:
        print(enrollment)
    else:
        continue

这似乎并不是处理任务的最有效方式。什么是更好的解决方案?

标签: pythonpython-3.xdictionary

解决方案


您可以使用理解(迭代器)来获取符合您的条件的字典子集。无论如何,这将是一个顺序搜索过程。

enrolments = [ {'account_key':1, 'other':99},
               {'account_key':2, 'other':98},
               {'account_key':1, 'other':97},
               {'account_key':1, 'other':96},
               {'account_key':3, 'other':95} ]

a = 1
found = (d for d in enrolments if d['account_key']==a)
print(*found,sep="\n")

{'account_key': 1, 'other': 99}
{'account_key': 1, 'other': 97}
{'account_key': 1, 'other': 96}

推荐阅读