Check if value already exists within list of dictionaries?

前端 未结 4 1959
野的像风
野的像风 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:12

    Maybe this helps:

    a = [{ 'main_color': 'red', 'second_color':'blue'},
         { 'main_color': 'yellow', 'second_color':'green'},
         { 'main_color': 'yellow', 'second_color':'blue'}]
    
    def in_dictlist((key, value), my_dictlist):
        for this in my_dictlist:
            if this[key] == value:
                return this
        return {}
    
    print in_dictlist(('main_color','red'), a)
    print in_dictlist(('main_color','pink'), a)
    

提交回复
热议问题