开发者

Python check if value is in a list of dicts

开发者 https://www.devze.com 2023-03-06 13:04 出处:网络
I have a list of dicts e.g. [{\'name\':\'Bernard\',\'age\':7},{\'name\':\'George\',\'age\':4},{\'name\':\'Reginald\',\'age\':6}]

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?


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.


The Proper Solution

There is a much more efficient way to do this than with looping. If you use operators.itemgetter you can do a simple if x in y check

#to simply check if the list of dicts contains the key=>value pair
'George' in map(itemgetter('name'), list_of_dicts)

#if you want to get the index 
index = map(itemgetter('name'), list_of_dicts).index("George") if 'George' in map(itemgetter('name'), list_of_dicts) else None


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 )


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


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)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号