Python列表的字典搜索

问题:

假设我有这个:

[
{"name": "Tom", "age": 10},
{"name": "Mark", "age": 5},
{"name": "Pam", "age": 7}
]

通过搜索“Pam”作为名称,我想检索相关的字典:{name:“Pam”,age:7}
如何实现这一点?

回答:

您可以使用generator expression

>>> dicts = [
...     { "name": "Tom", "age": 10 },
...     { "name": "Mark", "age": 5 },
...     { "name": "Pam", "age": 7 },
...     { "name": "Dick", "age": 12 }
... ]

>>> (item for item in dicts if item["name"] == "Pam").next()
{'age': 7, 'name': 'Pam'}

 
 
Code问答: http://codewenda.com/topics/python/
Stackoverflow: Python list of dictionaries search

*转载请注明本文链接以及stackoverflow的英文链接

发表评论

电子邮件地址不会被公开。 必填项已用*标注

7 + 1 =