我有以下字典列表。
people = [
{'name': "Tom", 'age': 10},
{'name': "Mark", 'age': 5},
{'name': "Pam", 'age': 7}
]
就在字典列表中搜索的性能而言,这将是最优化的方式。以下是一些不同的方法:
next((item for item in dicts if item["name"] == "Pam"), None)
或
filter(lambda person: person['name'] == 'Pam', people)
或
def search(name):
for p in people:
if p['name'] == name:
return p
或
def search_dictionaries(key, value, list_of_dictionaries):
return [element for element in list_of_dictionaries if element[key] == value]
也欢迎任何其他方法。谢谢。
最佳答案
对函数进行快速计时表明使用过滤器似乎是所有方法中最快的
%timeit filter(lambda person: person['name'] == 'Pam', people)
1000000 次循环,最好的 3 次:每次循环 263 ns
- 使用 next 产生 731ns 的时间
- 使用搜索方法产生 361ns 的时间
- 最后 seach_dictionaries 使用 811ns
关于python - 在字典列表中搜索的最有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38865201/