假设我有这个:
[
{"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}
如何做到这一点?
当前回答
将接受的答案放在函数中,以便于重用
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)
其他回答
people = [
{'name': "Tom", 'age': 10},
{'name': "Mark", 'age': 5},
{'name': "Pam", 'age': 7}
]
def search(name):
for p in people:
if p['name'] == name:
return p
search("Pam")
你可以通过使用Python中的filter和next方法来实现这一点。
方法过滤给定序列并返回一个迭代器。 Next方法接受迭代器并返回列表中的下一个元素。
所以你可以通过,
my_dict = [
{"name": "Tom", "age": 10},
{"name": "Mark", "age": 5},
{"name": "Pam", "age": 7}
]
next(filter(lambda obj: obj.get('name') == 'Pam', my_dict), None)
输出是,
{'name': 'Pam', 'age': 7}
注意:如果没有找到所搜索的名称,上述代码将返回None。
将接受的答案放在函数中,以便于重用
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éric Hamidi的回答很好。在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
>>>
为@FrédéricHamidi添加一点点。
如果你不确定字典列表中是否有键,这样做会有帮助:
next((item for item in dicts if item.get("name") and item["name"] == "Pam"), None)