字典搜索的 Python 列表 [英] Python list of dictionaries search
本文介绍了字典搜索的 Python 列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有这个:
<预><代码>[{姓名":汤姆",年龄":10},{姓名":马克",年龄":5},{姓名":帕姆",年龄":7}]并通过搜索Pam"作为名称,我想检索相关字典:{name: "Pam", age: 7}
如何实现?
解决方案
您可以使用 生成器表达式:
<预><代码>>>>字典 = [... { "name": "Tom", "age": 10 },... { "name": "Mark", "age": 5 },... { "name": "Pam", "age": 7 },... {姓名":迪克",年龄":12 }...]>>>next(如果 item["name"] == "Pam",则为 dicts 中的 item 的 item){'年龄':7,'姓名':'帕姆'}如果您需要处理不在那里的项目,那么您可以执行 user Matt 在他的评论中建议 并使用稍微不同的 API 提供默认值:
next((item for item in dicts if item["name"] == "Pam"), None)
并且要查找项目的索引,而不是项目本身,您可以enumerate() 列表:
next((i for i, item in enumerate(dicts) if item["name"] == "Pam"), None)
Assume I have this:
[
{"name": "Tom", "age": 10},
{"name": "Mark", "age": 5},
{"name": "Pam", "age": 7}
]
and by searching "Pam" as name, I want to retrieve the related dictionary: {name: "Pam", age: 7}
How to achieve this ?
解决方案
You can use a generator expression:
>>> dicts = [
... { "name": "Tom", "age": 10 },
... { "name": "Mark", "age": 5 },
... { "name": "Pam", "age": 7 },
... { "name": "Dick", "age": 12 }
... ]
>>> next(item for item in dicts if item["name"] == "Pam")
{'age': 7, 'name': 'Pam'}
If you need to handle the item not being there, then you can do what user Matt suggested in his comment and provide a default using a slightly different API:
next((item for item in dicts if item["name"] == "Pam"), None)
And to find the index of the item, rather than the item itself, you can enumerate() the list:
next((i for i, item in enumerate(dicts) if item["name"] == "Pam"), None)
这篇关于字典搜索的 Python 列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文