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.

4

4 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.

1

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?

2
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.

0

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.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Sophia Al-Mansoor

Sophia Al-Mansoor

Global Business & E-Commerce Reporter

Sophia analyzes international trade, startup ecosystems, retail transformation, and supply chain logistics for modern digital publications.

Share this article
Twitter Facebook Pinterest