简体   繁体   中英

Find a dictionary based on a key in list of dictionaries in python

I have a python list of dictionaries. How do I get a particular dictionary based on the key?

Example Input:

dict_input = [{"name":"kishore", "age":23}, {"name":"xyz", "age":21}]

Now how do I get the dictionary having key name and value kishore not going through entire list

I am expecting an O(1) look up.

It's impossible to get a item without iterating the list.

Using generator expression and next :

>>> dict_input = [{"name":"kishore", "age":23},{"name":"xyz", "age":21}]
>>> next((d for d in dict_input if d['name'] == 'kishore'), None)
{'age': 23, 'name': 'kishore'}

>>> next((d for d in dict_input if d['name'] == 'no-such-name'), None)
>>> next((d for d in dict_input if d['name'] == 'no-such-name'), None) == None
True

Build a dictionary if the lookup should be done multiple time and you don't want iterate whole list items.

>>> dict_input = {
...     "kishore": {"name":"kishore", "age":23},
...     "xyz": {"name":"xyz", "age":21}
... }
>>> dict_input["kishore"]
{'age': 23, 'name': 'kishore'}


>>> dict_input["no-such-name"]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'no-such-name'
>>> dict_input.get("no-such-name", "?")
'?'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM