Check if value already exists within list of dictionaries?

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

    Perhaps a function along these lines is what you're after:

     def add_unique_to_dict_list(dict_list, key, value):
      for d in dict_list:
         if key in d:
            return d[key]
    
      dict_list.append({ key: value })
      return value
    
    0 讨论(0)
  • 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)
    
    0 讨论(0)
  • 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!
    
    0 讨论(0)
  • 2020-11-27 11:21

    Here's one way to do it:

    if not any(d['main_color'] == 'red' for d in a):
        # does not exist
    

    The part in parentheses is a generator expression that returns True for each dictionary that has the key-value pair you are looking for, otherwise False.


    If the key could also be missing the above code can give you a KeyError. You can fix this by using get and providing a default value. If you don't provide a default value, None is returned.

    if not any(d.get('main_color', default_value) == 'red' for d in a):
        # does not exist
    
    0 讨论(0)
提交回复
热议问题