Reputation: 683
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
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
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
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