The Python Oracle

Python check if value is in a list of dicts

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Future Grid Looping

--

Chapters
00:00 Python Check If Value Is In A List Of Dicts
00:26 Accepted Answer Score 17
00:59 Answer 2 Score 0
01:07 Answer 3 Score 0
01:19 Answer 4 Score 1
01:35 Thank you

--

Full question
https://stackoverflow.com/questions/6041...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python

#avk47



ACCEPTED ANSWER

Score 17


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.




ANSWER 2

Score 1


I think a list comprehension would do the trick here too.

names = [i['name'] for i in l]

Then use it like so:

'Bernard' in names (True)
'Farkle' in names (False)

Or a one liner (If it's only one check)

'Bernard' in [i['name'] for i in l] (True)



ANSWER 3

Score 0


l = [{'name':'Bernard','age':7},{'name':'George','age':4},{'name':'Reginald','age':6}]
search_for = 'George'
print True in map(lambda person: True if person['name'].lower() == search_for.lower() else False, l )



ANSWER 4

Score 0


smf = [{'name':'Bernard','age':7},{'name':'George','age':4},{'name':'Reginald','age':6}]
def names(d):
    for i in d:
        for key, value in i.iteritems():
             if key == 'name':
                 yield value


In [5]: 'Bernard' in names(smf)
Out[5]: True


In [6]: 'Bernardadf' in names(smf)
Out[6]: False