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.
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 dicts 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 lists.
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.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With