Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python check if value is in a list of dicts

Tags:

python

I have a list of dicts e.g.

[{'name':'Bernard','age':7},{'name':'George','age':4},{'name':'Reginald','age':6}]

I'd like to check to see if a string value is the same as the 'name' value in any of the dicts in the list. For example 'Harold' would be False, but 'George' would be True.

I realise I could do this by looping through each item in the list, but I was wondering if there was a more efficient way?

like image 682
chrism Avatar asked May 18 '11 08:05

chrism


1 Answers

No, there cannot be a more efficient way if you have just this list of dicts.

However, if you want to check frequently, you can extract a dictionary with name:age items:

l = [{'name':'Bernard','age':7},{'name':'George','age':4},{'name':'Reginald','age':6}]
d = dict((i['name'], i['age']) for i in l)

now you have d:

{'Bernard': 7, 'George': 4, 'Reginald': 6}

and now you can check:

'Harold' in d   -> False
'George' in d   -> True

It will be much faster than iterating over the original list.

like image 136
eumiro Avatar answered Oct 18 '22 19:10

eumiro