如何使用我想要获取的字典的一个键/值对从字典列表中访问字典



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

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

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

一些选项:

1-像这里一样使用循环,尽管不使用continue可以写得更简单。

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

2-使用生成器表达式和next

enrollment = next(e for e in enrollments if e['account_key'] == a)
print(enrollment)

3-将字典列表转换为字典的字典。如果您必须多次执行此操作并且每个account_key

只有一个值,则这是一个不错的选择。
accounts = {
enrollment['account_key']: enrollment
for enrollment in enrollments
}
print(accounts[a])

4-和上面一样,但是如果同一个键有多个值,你可以使用字典列表的字典。

accounts = defaultdict(list)
for enrollment in enrollments:
accounts[enrollment['account_key']].append(enrollment)
for enrollment in accounts[a]:
print(enrollment)

您可以使用推导式(迭代器)来获得符合您的标准的字典子集。在任何情况下,这将是一个顺序的搜索过程。

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}