Python列表的字典搜索 [英] Python list of dictionaries search
本文介绍了Python列表的字典搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有这个:
[
{"name": "Tom", "age": 10},
{"name": "Mark", "age": 5},
{"name": "Pam", "age": 7}
]
并通过搜索Pam作为名称,我想检索相关的字典:{name:Pam年龄:7}
and by searching "Pam" as name, I want to retrieve the related dictionary: {name: "Pam", age: 7}
如何实现?
推荐答案
你可以使用生成器表达式:
>>> 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'}
这篇关于Python列表的字典搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文