Python Dictionary Check If Key Exists

How to check if key exists in python dictionary and how to merge two dictionary ?

We use dictionary to store data in key value pair . It is a unordered collection . Unordered mean key value pair can be in any order . But it is changeable and does not allow duplicates . Python dictionary is a built-in container for storing key value pair data . Basic purpose of this story is to find out how to check if key exists in python dictionary and how to merge two dictionary . Let’s start with basic of it.

Dictionaries are written with curly brackets, and have keys and values:

my_dict = {
"gadget":"Smart phone",
"vehicle":"Bike",
"timepass":"twitter",
"movie":"A Beautiful Mind",
"Book":"A Tale of two City",
"score":81,
"colors":['Red','Green','Blue'],
"is_red":True
}

Access Items

we can access items by following ways -

  1. Items can be access by putting key in square[] bracket .
  2. By using get() method .
print(my_dict['gadget'])
print(my_dict.get('colors'))

items() method used to get each item in form of tuple . values() method used to get list of values of dictionary . keys() method used to get list of keys of dictionary .

print(my_dict.items())
print(my_dict.values())
print(my_dict.keys())

Add Items

We add new item to dictionary by using new key as index assigning value to it. update() method is also used to update dictionary as well as add new item .

my_dict['framework'] = 'Django'
my_dict.update({'language':'python'})

Removing Items

Item with specific key can be removed by pop() method . popitem() method is used to remove random item but it is valid python less than 3.7 . In python 3.7 and above popitem() remove last item of dictionary .

print(my_dict.pop('colors'))
my_dict.popitem()
print(my_dict)

del keyword and clear() method used to delete dictionary completely . We can also delete item with specific key using del keyword .

del my_dict['movie']
del my_dict
my_dict.clear()

Merge Two Dictionaries

We can merge two dictionaries using different methods . lets define two dictionaries as dict1 and dict2 .

dict1 = {
"name":"XYZ",
"country":"India"
}
dict2 = {
"city":"New Delhi",
"mobile":1234567890
}

In python2 and above we can use copy(),update() and extend() method to add dictionary to another dictionary .

We can combine dictionaries using items().

dict3 = dict(dict1.items() + dict2.items())
"""
for nested dictionaries we can use we have to convert dict item into list and then add .
"""
dict3 = dict(list(dict1.items()) + list(dict2.items()))#using update() method
dict3 = dict1.copy()
dict3.update(dict2)
#using extend() method
for key,value in dict1.items():
if key in dict2:
dict2[key].extend(value)
else:
dict2[key] = value

For python3 and above we can use **astertik for merging dictionaries .

dict3 = {**dict1 , **dict2}

For python 3.9 and above we can use merge operator( | ) to combine dictionaries .

dict3 = dict1 | dict2

Check if key exists in dictionary

A dictionary key can be numeric or string value . But we can’t use object like list which are mutable in nature as key . Let’s see the following ways to check if key exists .

By using in operator . It returns True or False based on exitstence .

if 'colors' in my_dict:     
print('Found')
else:
print('Not Found')

By using get() method . It returns None if key not found in dictionary .

if my_dict.get('colors'):     
print('Found')
else:
print('Not Found')

By using keys() method . It returns list of existing keys of dictionary .

if 'colors' in my_dict.keys():     
print('Found')
else:
print('Not Found')

By using has_key() method . It returns True or False based on key existence .

if my_dict.has_key('colors'):     
print('Found')
else:
print('Not Found')

For Handling Key Error exception we can put code into try except block .

try:     
my_dict[key]
except KeyError as err:
print('Key not found')

Conclusion

In this article we cover dictionary creation, adding items into dictionary, removing items from dictionary, merging two dictionaries using different ways , checking if key exists in dictionary and key error exception handling .

Thanks!!