Reputation: 13721
I have a list of dictionaries in the format:
mylist1 = [{'model': 'one'}, {'color': 'blue'}, {'age': 23}]
Is there a way I can look up a dictionary based on its key? For something I want to do something like (pseudocode):
mylist1['model'] #should return {'model': 'one'}
The reason why I am not doing mylist[0]['model']
is because the list elements are not always in that order.
Upvotes: 2
Views: 39639
Reputation: 6781
Using list comprehension
, find all dictionaries
in the list
that contain that key
:
>>> mylist1 = [{'model': 'one'}, {'color': 'blue'}, {'age': 23}, {'model': 'two'}]
>>> key = 'model'
>>> [ ele for ele in mylist1 if key in ele ]
=> [{'model': 'one'}, {'model': 'two'}]
NOTE TO OP : as others have pointed out, its ofcourse quite redundant to have a list of dictionaries; unless you have dictionaries with duplicate keys.
Upvotes: 1
Reputation: 1875
key = "model"
d = [ x for x in mylist if key in x ]
If you want just one match:
key = "model"
d = next( x for x in mylist if key in x )
Second one uses generator, so it just finds first match and then stops.
Upvotes: 1
Reputation: 402363
Collapse your dictionary.
d = {k : v for d in mylist1 for k, v in d.items()}
d
{'age': 23, 'color': 'blue', 'model': 'one'}
Now, just lookup in constant, O(1)
time.
d['model']
'one'
By keeping multiple disjoint dict
s in the same list, you're defeating their purpose in the first place.
If you have multiple possible values with the same keys, use a dict
of list
s.
d = {}
for dct in mylist1:
for k, v in dct.items():
d.setdefault(k, []).append(v)
d
{'age': [23], 'color': ['blue'], 'model': ['one']}
Supports multiple values with the same key without overwriting entries, as the previous one would've done.
Upvotes: 5
Reputation: 81594
The pseudocode you provided is impossible unless you subclass (or monkey patch) list
(otherwise you'd get an error that list indices must be integers and not strings).
However you could write a function such as
def find(li, key):
for d in li:
if key in d:
return d
It will find and return the first dictionary that contains the given key, and can be easily modified to return a list of dictionaries if the keys are not unique.
it looks like you are using dictionaries wrong. Why do you have a list of dictionaries, each having (apparently) unique keys, and not a single dictionary?
Upvotes: 4