[英]How to access the dictionary from a list of dictionaries using one key/value pair of the dictionary that I want to fetch
I have a list of dictionaries, which all have the same keys.我有一个字典列表,它们都有相同的键。 I have a specific value of one key and want to access/print the dictionary, which contains this specific value.
我有一个键的特定值,想访问/打印包含此特定值的字典。 I couldn't think of any way, other than looping around the whole list, checking the corresponding value of the key and printing it out using if statement, that is if the given value matched the key.
除了遍历整个列表,检查键的相应值并使用if语句打印出来之外,我想不出任何方法,即给定的值是否与键匹配。
for enrollment in enrollments:
if enrollment['account_key'] == a:
print(enrollment)
else:
continue
This does not really seem the most efficient way to handle the task.这似乎并不是处理任务的最有效方式。 What would be a better solution?
什么是更好的解决方案?
Some options:一些选项:
1- Use the loop like you do here, although this could be written simpler without the continue. 1- 像这里一样使用循环,尽管如果没有 continue,这可以写得更简单。
for enrollment in enrollments:
if enrollment['account_key'] == a:
print(enrollment)
2- Use a generator expression and next
2-使用生成器表达式和
next
enrollment = next(e for e in enrollments if e['account_key'] == a)
print(enrollment)
3- Convert the list of dictionaries into a dictionary of dictionaries. 3- 将字典列表转换为字典字典。 This is a good option if you have to do this operation many times and there is only one value for each
account_key
如果您必须多次执行此操作并且每个
account_key
只有一个值,这是一个不错的选择
accounts = {
enrollment['account_key']: enrollment
for enrollment in enrollments
}
print(accounts[a])
4- Same as above, but if there are multiple values for the same key, you can use a dict of lists of dicts. 4- 同上,但如果同一个键有多个值,您可以使用字典列表。
accounts = defaultdict(list)
for enrollment in enrollments:
accounts[enrollment['account_key']].append(enrollment)
for enrollment in accounts[a]:
print(enrollment)
You can use a comprehension (iterator) to get the subset of dictionaries that match your criteria.您可以使用理解(迭代器)来获取符合您的条件的字典子集。 In any case this will be a sequential search process.
无论如何,这将是一个顺序搜索过程。
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.