Python check if value is in a list of dicts

后端 未结 5 1420
陌清茗
陌清茗 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:38

    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.

提交回复
热议问题