views:

167

answers:

3

I don't think this question has been asked in this form on SO before.

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

a = [{ 'main_color': 'red', 'second_color':'blue'}, { 'main_color': 'yellow', 'second_color':'green'}, { 'main_color': 'yellow', 'second_color':'blue'}]

I'd like to check whether a dictionary with a particular key/value already exists in the list, as follows:

// is a dict with 'main_color'='red' in the list already?
// if not: add item

Thanks!

+6  A: 

Here's one way to do it:

if not any(d.get('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.

Mark Byers
Very nice. Thanks!
AP257
A: 

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
Cameron
A: 

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)
Tony Veijalainen