Reputation: 1748
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.
Upvotes: 0
Views: 85
Reputation: 369074
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", "?")
'?'
Upvotes: 1