Reputation: 95
I have list of dictionaries of
a = [{'id':'1','name':'john'}, {'id':'2','name':'johns'}, {'id':'3','name':'rock'}
I want to display the dictionary of using the id
value '2'
to search the dictionary and the wanted output is like this
{'id':'2','name':'johns'}
How to display the dictionary to be like that?
Upvotes: 0
Views: 41
Reputation: 6298
You can use list comprehension, in O(n):
a = [{'id':'1','name':'john'}, {'id':'2','name':'johns'}, {'id':'3','name':'rock'}]
# [{'id': '2', 'name': 'johns'}]
print([d for d in a if d['id'] == '2'])
However representing data as dictionary is more efficient, in O(1):
a = {'1': {'name' : 'john'}, '2': {'name' : 'johns'}, '3': {'name' : 'rock'}}
# {'name': 'johns'}
print(a['2'])
Upvotes: 2