Add an item to a dictionary if the key does not exist in Python

In this Python tutorial, we are going to learn how to add an item to a dictionary if the key does not exist in it. Before proceeding towards this let’s understand what is a dictionary in python and how it will work.

Dictionary is used to store data in key: value pair form. It is an ordered collection of items/objects in which we can change values but duplicates are not allowed.
Example:

dict = {'a':1,'b':2,'c':3}

Here data is in the form of key value pairs.

Now let’s see how to add a key if the key is not present in the dictionary. Here we have two methods first using setdefault() function and the other by use of not in operator

Adding item by the use of setdefault() function

dict = {"Name":"Rohan", "Hairs":"Black", "Age":20, "Height":175,}
print(dict) # Initally
dict.setdefault('Weight', 55)
print(dict) # After adding weight

Output

{'Name': 'Rohan', 'Hairs': 'Black', 'Age': 20, 'Height': 175}
{'Name': 'Rohan', 'Hairs': 'Black', 'Age': 20, 'Height': 175, 'Weight': 55}

Here we have taken one dictionary which contains information about the person named ‘Rohan’. As you can see here setdefault() function takes parameter as key: value if the value is not given it will consider it None. Code and output are shown below.

dict.setdefault('Weight')
print(dict)

Output

{'Name': 'Rohan', 'Hairs': 'Black', 'Age': 20, 'Height': 175, 'Weight': None}

Adding item by checking of  ‘not in’ operator

Here we are taking the same dictionary as above.

dict = {"Name":"Rohan", "Hairs":"Black", "Age":20, "Height":175,}
#cheking presence of key in dictonary
if 'Weight' not in dict:
    dict['Weight'] = '60'
print(dict)

Output

{'Name': 'Rohan', 'Hairs': 'Black', 'Age': 20, 'Height': 175, 'Weight': '60'}

Here you can see we are using if condition and not in operator for checking whether the key is present in the dictionary or not. If not present then we are adding it to the dictionary as shown in the code. And lastly printing updated dictionary.

Leave a Reply

Your email address will not be published.