Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lookup dictionary based on python key

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.

like image 989
Trung Tran Avatar asked Dec 04 '25 18:12

Trung Tran


2 Answers

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.

like image 177
cs95 Avatar answered Dec 06 '25 08:12

cs95


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.

But

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?

like image 26
DeepSpace Avatar answered Dec 06 '25 08:12

DeepSpace



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!