繁体   English   中英

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

[英]How to access the dictionary from a list of dictionaries using one key/value pair of the dictionary that I want to fetch

我有一个字典列表,它们都有相同的键。 我有一个键的特定值,想访问/打印包含此特定值的字典。 除了遍历整个列表,检查键的相应值并使用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}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM