字典搜索的Python列表

♀尐吖头ヾ 提交于 2020-02-26 11:25:44

假设我有这个:

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

并通过搜索“ Pam”作为名称,我想检索相关的词典: {name: "Pam", age: 7}

如何实现呢?


#1楼

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

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

#2楼

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

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

#3楼

@FrédéricHamidi的回答很好。 在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
>>>

#4楼

向@FrédéricHamidi添加一点点。

如果您不确定某个键是否在字典列表中,可以使用以下方法:

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

#5楼

这是一个使用迭代遍历列表的比较,使用filter + lambda或重构(如果需要或对您的情况有效)的代码将您的代码用于命令,而不是命令列表

import time

# Build list of dicts
list_of_dicts = list()
for i in range(100000):
    list_of_dicts.append({'id': i, 'name': 'Tom'})

# Build dict of dicts
dict_of_dicts = dict()
for i in range(100000):
    dict_of_dicts[i] = {'name': 'Tom'}


# Find the one with ID of 99

# 1. iterate through the list
lod_ts = time.time()
for elem in list_of_dicts:
    if elem['id'] == 99999:
        break
lod_tf = time.time()
lod_td = lod_tf - lod_ts

# 2. Use filter
f_ts = time.time()
x = filter(lambda k: k['id'] == 99999, list_of_dicts)
f_tf = time.time()
f_td = f_tf- f_ts

# 3. find it in dict of dicts
dod_ts = time.time()
x = dict_of_dicts[99999]
dod_tf = time.time()
dod_td = dod_tf - dod_ts


print 'List of Dictionries took: %s' % lod_td
print 'Using filter took: %s' % f_td
print 'Dict of Dicts took: %s' % dod_td

输出是这样的:

List of Dictionries took: 0.0099310874939
Using filter took: 0.0121960639954
Dict of Dicts took: 4.05311584473e-06

结论:在这些情况下,显然拥有字典词典是最有效的搜索方式,在这种情况下,您知道您将仅通过id进行搜索。 有趣的是,使用过滤器是最慢的解决方案。

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!