Check if value already exists within list of dictionaries?


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
Asked By: AP257



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
Answered By: Mark Byers

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
Answered By: Cameron

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 entry in my_dictlist:
        if entry[key] == value:
            return entry
    return {}

print in_dictlist('main_color','red', a)
print in_dictlist('main_color','pink', a)
Answered By: Tony Veijalainen

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!')


Answered By: Amitsas1

Following works out for me.

    #!/usr/bin/env python
    a = [{ 'main_color': 'red', 'second_color':'blue'},
    { 'main_color': 'yellow', 'second_color':'green'},
    { 'main_color': 'yellow', 'second_color':'blue'}]

    found_event = next(
                lambda x: x['main_color'] == 'red',
      #return this dict when not found

    if found_event:

    $python  /tmp/x
    {'main_color': 'red', 'second_color': 'blue'}
Answered By: samtoddler

Just another way to do what the OP asked:

 if not filter(lambda d: d['main_color'] == 'red', a):
     print('Item does not exist')

filter would filter down the list to the item that OP is testing for. The if condition then asks the question, "If this item is not there" then execute this block.

Answered By: Gourav Chawla

I think a check if the key exists would be a bit better, as some commenters asked under the preferred answer enter link description here

So, I would add a small if clause at the end of the line:

input_key = 'main_color'
input_value = 'red'

if not any(_dict[input_key] == input_value for _dict in a if input_key in _dict):
    print("not exist")

I’m not sure, if wrong but I think the OP asked to check, if the key-value pair exists and if not the key value pair should be added.

In this case, I would suggest a small function:

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

b = None

c = [{'second_color': 'blue'},
     {'second_color': 'green'}]

c = [{'main_color': 'yellow', 'second_color': 'blue'},
     {'second_color': 'green'},

def in_dictlist(_key: str, _value :str, _dict_list = None):
    if _dict_list is None:
        # Initialize a new empty list
        # Because Input is None
        # And set the key value pair
        _dict_list = [{_key: _value}]
        return _dict_list

    # Check for keys in list
    for entry in _dict_list:
        # check if key with value exists
        if _key in entry and entry[_key] == _value:
            # if the pair exits continue
            # if not exists add the pair
            entry[_key] = _value
    return _dict_list

_a = in_dictlist("main_color", "red", a )
_b = in_dictlist("main_color", "red", b )
_c = in_dictlist("main_color", "red", c )


_a=[{'main_color': 'red', 'second_color': 'blue'}, {'main_color': 'red', 'second_color': 'green'}, {'main_color': 'red', 'second_color': 'blue'}]
_b=[{'main_color': 'red'}]
_c=[{'main_color': 'red', 'second_color': 'blue'}, {'main_color': 'red'}, {'second_color': 'green', 'main_color': 'red'}, {'main_color': 'red'}]
Answered By: Rene
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.