假设我有这个:
[
{"name": "Tom", "age": 10},
{"name": "Mark", "age": 5},
{"name": "Pam", "age": 7}
]
通过搜索“Pam”作为名称,我想检索相关的字典:{name:“Pam”,年龄:7}
如何做到这一点?
假设我有这个:
[
{"name": "Tom", "age": 10},
{"name": "Mark", "age": 5},
{"name": "Pam", "age": 7}
]
通过搜索“Pam”作为名称,我想检索相关的字典:{name:“Pam”,年龄:7}
如何做到这一点?
当前回答
dicts=[
{"name": "Tom", "age": 10},
{"name": "Mark", "age": 5},
{"name": "Pam", "age": 7}
]
from collections import defaultdict
dicts_by_name=defaultdict(list)
for d in dicts:
dicts_by_name[d['name']]=d
print dicts_by_name['Tom']
#output
#>>>
#{'age': 10, 'name': 'Tom'}
其他回答
鸭子将比列表理解或过滤器快得多。它在你的对象上建立一个索引,这样查找就不需要扫描每一个项目。
PIP安装鸭
from ducks import Dex
dicts = [
{"name": "Tom", "age": 10},
{"name": "Mark", "age": 5},
{"name": "Pam", "age": 7}
]
# Build the index
dex = Dex(dicts, {'name': str, 'age': int})
# Find matching objects
dex[{'name': 'Pam', 'age': 7}]
结果:[{'name': 'Pam', 'age': 7}]
我的第一个想法是,你可能想要考虑为这些字典创建一个字典……举个例子,如果你要多次搜索它。
然而,这可能是一个不成熟的优化。有什么问题:
def get_records(key, store=dict()):
'''Return a list of all records containing name==key from our store
'''
assert key is not None
return [d for d in store if d['name']==key]
我会像这样创建一个字典的字典:
names = ["Tom", "Mark", "Pam"]
ages = [10, 5, 7]
my_d = {}
for i, j in zip(names, ages):
my_d[i] = {"name": i, "age": j}
或者,使用与问题中完全相同的信息:
info_list = [{"name": "Tom", "age": 10}, {"name": "Mark", "age": 5}, {"name": "Pam", "age": 7}]
my_d = {}
for d in info_list:
my_d[d["name"]] = d
然后你可以执行my_d["Pam"],得到{"name": "Pam", "age": 7}
将接受的答案放在函数中,以便于重用
def get_item(collection, key, target):
return next((item for item in collection if item[key] == target), None)
也可以写成
get_item_lambda = lambda collection, key, target : next((item for item in collection if item[key] == target), None)
结果
key = "name"
target = "Pam"
print(get_item(target_list, key, target))
print(get_item_lambda(target_list, key, target))
#{'name': 'Pam', 'age': 7}
#{'name': 'Pam', 'age': 7}
如果键可能不在目标字典中,请使用dict。get和避免KeyError
def get_item(collection, key, target):
return next((item for item in collection if item.get(key, None) == target), None)
get_item_lambda = lambda collection, key, target : next((item for item in collection if item.get(key, None) == target), None)
为@FrédéricHamidi添加一点点。
如果你不确定字典列表中是否有键,这样做会有帮助:
next((item for item in dicts if item.get("name") and item["name"] == "Pam"), None)