Relax ZeroC
Relax ZeroC

Reputation: 683

python - Quickly search the dict in the list

I have many dictionaries in a list, like below:

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

How can I quickly get the value of name is a parameter.

ex : if I hope to get name is 'Received', and get the dictionary:

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

Upvotes: 2

Views: 92

Answers (3)

Don
Don

Reputation: 17636

I'd build a lookup dictionary at first:

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

Of course, this works if there are no duplicate names.

Alternative syntax:

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

Upvotes: 2

ettanany
ettanany

Reputation: 19816

list comprehension is the pythonic way, but this is just another option using filter():

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

Output:

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

Upvotes: 1

jpp
jpp

Reputation: 164773

A list comprehension would work. This will provide a list of all dictionaries where d['name'] == 'Received':

[x for x in mylist if x['name'] == 'Received']

Upvotes: 5

Related Questions