python - 快速搜索列表中的dict

时间:2018-01-31 10:29:09

标签: python list dictionary

我在列表中有很多词典,如下所示:

mylist = [{'name': 'Delivered-To', 'value': '123'},
          {'name': 'Received', 'value': 'abc'},
          {'name': 'Payload', 'value': 'xxxxxx'}]

如何快速获取name的值是一个参数。

例如:如果我希望得到名字“收到”,并获取字典:

{'name': 'Received', 'value': 'abc'}

3 个答案:

答案 0 :(得分:5)

列表理解可行。这将提供d['name'] == 'Received'

所有词典的列表
[x for x in mylist if x['name'] == 'Received']

答案 1 :(得分:2)

我首先要构建一个查找字典:

mylist = [{'name': 'Delivered-To', 'value': '123'},
          {'name': 'Received', 'value': 'abc'},
          {'name': 'Payload', 'value': 'xxxxxx'}]

lookup_dict = dict((d['name'], d['value']) for d in mylist)

>>> print lookup_dict
{'Received': 'abc', 'Delivered-To': '123', 'Payload': 'xxxxxx'}

>>> print lookup_dict['Received']
abc

当然,如果没有重复的名称,这是有效的。

替代语法:

lookup_dict = {d['name']: d['value']  for d in mylist}

答案 2 :(得分:1)

list comprehension是pythonic方式,但这只是使用filter()的另一种选择:

list(filter(lambda x: x['name'] == 'Received', mylist))
# [{'name': 'Received', 'value': 'abc'}]

<强>输出:

>>> result = filter(lambda x: x['name'] == 'Received', mylist)
>>> result
<filter object at 0x00000198FF419C88>
>>> next(result)
{'name': 'Received', 'value': 'abc'}