假设我有这个:

[
  {"name": "Tom", "age": 10},
  {"name": "Mark", "age": 5},
  {"name": "Pam", "age": 7}
]

通过搜索“Pam”作为名称,我想检索相关的字典:{name:“Pam”,年龄:7}

如何做到这一点?


当前回答

这是在字典列表中搜索值的一般方法:

def search_dictionaries(key, value, list_of_dictionaries):
    return [element for element in list_of_dictionaries if element[key] == value]

其他回答

我测试了各种方法来遍历字典列表并返回键x具有特定值的字典。

结果:

速度:列表推导>生成器表达式>>常规列表迭代>>>过滤器。 所有的比例都与列表中的字典数量线性(10x列表大小-> 10x时间)。 对于大量(数千个)键,每个字典的键不会显著影响速度。请看我计算的图表:https://imgur.com/a/quQzv(方法名称见下文)。

所有测试均使用Python 3.6.4, W7x64完成。

from random import randint
from timeit import timeit


list_dicts = []
for _ in range(1000):     # number of dicts in the list
    dict_tmp = {}
    for i in range(10):   # number of keys for each dict
        dict_tmp[f"key{i}"] = randint(0,50)
    list_dicts.append( dict_tmp )



def a():
    # normal iteration over all elements
    for dict_ in list_dicts:
        if dict_["key3"] == 20:
            pass

def b():
    # use 'generator'
    for dict_ in (x for x in list_dicts if x["key3"] == 20):
        pass

def c():
    # use 'list'
    for dict_ in [x for x in list_dicts if x["key3"] == 20]:
        pass

def d():
    # use 'filter'
    for dict_ in filter(lambda x: x['key3'] == 20, list_dicts):
        pass

结果:

1.7303 # normal list iteration 
1.3849 # generator expression 
1.3158 # list comprehension 
7.7848 # filter

在我看来,这是最python的方式:

people = [
{'name': "Tom", 'age': 10},
{'name': "Mark", 'age': 5},
{'name': "Pam", 'age': 7}
]

filter(lambda person: person['name'] == 'Pam', people)

result(在Python 2中作为列表返回):

[{'age': 7, 'name': 'Pam'}]

注意:在python3中,返回一个filter对象。所以python3的解决方案是:

list(filter(lambda person: person['name'] == 'Pam', people))

我会像这样创建一个字典的字典:

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}

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")

你可以使用生成器表达式:

>>> 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在他的评论中建议的事情,并使用稍微不同的API提供默认值:

next((item for item in dicts if item["name"] == "Pam"), None)

并且要查找项目的索引,而不是项目本身,您可以枚举()列表:

next((i for i, item in enumerate(dicts) if item["name"] == "Pam"), None)