Check if value already exists within list of dictionaries?

前端 未结 4 1949
野的像风
野的像风 2020-11-27 10:28

I\'ve got a Python list of dictionaries, as follows:

a = [
    {\'main_color\': \'red\', \'second_color\':\'blue\'},
    {\'main_color\': \'yellow\', \'secon         


        
4条回答
  •  一生所求
    2020-11-27 11:16

    Based on @Mark Byers great answer, and following @Florent question, just to indicate that it will also work with 2 conditions on list of dics with more than 2 keys:

    names = []
    names.append({'first': 'Nil', 'last': 'Elliot', 'suffix': 'III'})
    names.append({'first': 'Max', 'last': 'Sam', 'suffix': 'IX'})
    names.append({'first': 'Anthony', 'last': 'Mark', 'suffix': 'IX'})
    
    if not any(d['first'] == 'Anthony' and d['last'] == 'Mark' for d in names):
    
        print('Not exists!')
    else:
        print('Exists!')
    

    Result:

    Exists!
    

提交回复
热议问题