Python词典搜索列表假设我有这个:[{"name": "Tom", "age": 10},{"name": "Mark", "age": 5},{"name": "Pam", "age": 7}]并通过搜索“Pam”作为名称,我想检索相关的字典: {name: "Pam", age: 7}怎么做到这一点?
3 回答
繁星点点滴滴
TA贡献1803条经验 获得超3个赞
这对我来说是最pythonic的方式:
people = [{'name': "Tom", 'age': 10},{'name': "Mark", 'age': 5},{'name': "Pam", 'age': 7}]filter(lambda person: person['name'] == 'Pam', people)
结果(在Python 2中作为列表返回):
[{'age': 7, 'name': 'Pam'}]
注意:在Python 3中,返回一个过滤器对象。所以python3解决方案将是:
list(filter(lambda person: person['name'] == 'Pam', people))
DIEA
TA贡献1820条经验 获得超2个赞
在Python 3.x中,语法.next()
略有改变。因此略有修改:
>>> 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'}
正如@Matt的评论中所提到的,您可以添加默认值:
>>> next((item for item in dicts if item["name"] == "Pam"), False){'name': 'Pam', 'age': 7}>>> next((item for item in dicts if item["name"] == "Sam"), False)False>>>
添加回答
举报
0/150
提交
取消