find an item inside a list of dictionaries

  • A+
Category:Languages

Say I have a list of dictionaries. each dict in the list has 3 elements. Name, id and status.

list_of_dicts = [{'id':1, 'name':'Alice', 'status':0},{'id':2, 'name':'Bob', 'status':0},{'id':3, 'name':'Robert', 'status':1}] 

so I get:

In[20]: print list_of_dicts Out[20]:  [{'id': 1, 'name': 'Alice', 'status': 0},  {'id': 2, 'name': 'Bob', 'status': 0},  {'id': 3, 'name': 'Robert', 'status': 1}] 

If i recieve a name, how can I get its status without iterating on the list?
e.g. I get 'Robert' and I want to output 1.
thank you.

 


As you found you have to iterate (unless you are able to change your data structure to an enclosing dict) why don't you just do it?

>>> [d['status'] for d in list_of_dicts if d['name']=='Robert'] [1] 

Despite this, I recommend considering a map type (like dict) every time you see some 'id' field in a proposed data structure. If it's there you probably want to use it for general identification, instead of carrying dicts around. They can be used for relations also, and transfer easily into a relational database if you need it later.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: