Python check if value is in a list of dicts

后端 未结 5 1424
陌清茗
陌清茗 2021-02-08 23:56

I have a list of dicts e.g.

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

I\'d like to c

5条回答
  •  别那么骄傲
    2021-02-09 00:31

    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
    

提交回复
热议问题