How to find if value is present in List of Dictionary

How to find if value is present in List of Dictionary
entity_name_dict = [{'user_id': 'ramesh', 'name': 'Ramesh Patnaik', 'mail_id': 'connect_abc@abc.com'},
                    {'user_id': 'suresh', 'name': 'Suresh Patel', 'mail_id': 'connect_abc@abc.com'},
                    {'user_id': 'sanjana', 'name': 'Sanajana Damani', 'mail_id': 'connect_abc@abc.com'}
                    ]

Let say you have a list of dictionary items like the above and you need to check in one line if any particular value is present for a given key. Like if you want to know where ‘suresh’ exist as a user in the list of dictionaries.

There are multiples way to do it, easiest would be putting a loop over the item of List, then checking the given dictionary key and comparing its value to given input value.

But we will try to do it in pythonic way in a single line statement. First way:

class ListDictAdvanceOp:
    def __init__(self):
        self._found = False

    def find_value_present_in_list_of_dict_way1(self, key, value_to_compare, dict_kv):
        if any(dict_item[key] == value_to_compare for dict_item in dict_kv):
            self._found = True
        else:
            self._found = False
        return self._found

If you see the logic inside the function, “find_value_present_in_list_of_dict_way1”,

if any(dict_item[key] == value_to_compare for dict_item in dict_kv):

  • it iterates over the dictionary list and then it checks for each dictionary if dict_item[‘user_id’] == ‘suresh’, if it found it return True
  • Then we use ‘any’, which will return true if any of the value returned from expression is true.

Lets call this function and see the result

if __name__ == '__main__':

    obj_list_dict_adv_op = ListDictAdvanceOp()
    entity_name_dict = [{'user_id': 'ramesh', 'name': 'Ramesh Patnaik', 'mail_id': 'connect_abc@abc.com'},
                        {'user_id': 'suresh', 'name': 'Suresh Patel', 'mail_id': 'connect_abc@abc.com'},
                        {'user_id': 'sanjana', 'name': 'Sanajana Damani', 'mail_id': 'connect_abc@abc.com'}
                        ]

    # First way of finding if key value is existing in list of dictionary item
    found_flag1 = obj_list_dict_adv_op.find_value_present_in_list_of_dict_way1('user_id', 'suresh', entity_name_dict)
    print(f"Found Status: {found_flag1}")

    found_flag2 = obj_list_dict_adv_op.find_value_present_in_list_of_dict_way1('user_id', 'happy', entity_name_dict)
    print(f"Found Status: {found_flag2}")

    found_flag3 = obj_list_dict_adv_op.find_value_present_in_list_of_dict_way1('userid', 'happy', entity_name_dict)
    print(f"Found Status: {found_flag3}")

If you see we are passing three parameter to the function call the key which is “user_id” and value which we want to find and dictionary list where we need to find of value exist.

The first two call to function will be successful but the last call to function will fail with “KeyError” that is because we are passing “userid” as key instead of “user_id”, so it could not able to get the key from the dictionary.

Found Status: True

Found Status: False

File “C:\PyProjects\myProj2\ListDict\FindingValueInlistOfDict.py”, line 6, in <genexpr>

    if any(dict_item[key] == value_to_compare for dict_item in dict_kv):

           ~~~~~~~~~^^^^^

KeyError: ‘userid’

So, to rectify that we can change a little in our logic

def find_value_present_in_list_of_dict_way2(self, key, value_to_compare, dict_kv):
    if any(dict_item.get(key, None) == value_to_compare for dict_item in dict_kv):
        self._found = True
    else:
        self._found = False
    return self._found

So here we use dict_item.get(key, None) instead of dict_item[key]

# Second way of finding if key value is existing in list of dictionary item
found_flag = obj_list_dict_adv_op.find_value_present_in_list_of_dict_way1('user_id', 'suresh', entity_name_dict)
print(f"Found Status: {found_flag}")

found_flag = obj_list_dict_adv_op.find_value_present_in_list_of_dict_way2('user_id', 'happy', entity_name_dict)
print(f"Found Status: {found_flag}")

found_flag = obj_list_dict_adv_op.find_value_present_in_list_of_dict_way2('userid', 'happy', entity_name_dict)
print(f"Found Status: {found_flag}")

The result would be:

Found Status: True

Found Status: False

Found Status: False

Leave a Reply

Your email address will not be published. Required fields are marked *