Python | Add to Dictionary If Key doesn’t exist

This article will discuss how to add key-value pairs in the dictionary only when Key does not exist.

Add a key-value pair to the dictionary if Key doesn’t exist

Suppose we have a dictionary of string and integers,

# Dictionary of strings and ints
word_freq = {"Hello": 56,
             "at": 23,
             "test": 43,
             "this": 43}

Now, if we want to add a new pair {‘why’: 10} to this dictionary, then it should be added without any problem. It is because the key ‘why’ does not exist in the dictionary yet. Whereas when we try to add a new pair {‘at’: 11} to this dictionary, then it should not be added because key ‘at’ already exists in the dictionary.

To have this kind of behavior, before adding a key-value pair to the dictionary, we need to check if the Key already exists in the dictionary or not. If Key does not exist in the dictionary yet, only add the new pair; otherwise, skip. For example,

# Dictionary of strings and ints
word_freq = {"Hello": 56,
             "at": 23,
             "test": 43,
             "this": 43}

key = 'how'
value = 50

if key not in word_freq:
    word_freq.update({key: value})
else:
    print('Key already exist')

print(word_freq)

Output:

{'Hello': 56, 
 'at': 23,
 'test': 43,
 'this': 43,
 'how': 50}

We tried to add a key-value pair whose Key does not exist in the dictionary. Therefore, it got added to the dictionary successfully.

Now let’s try to add a pair whose Key already exists in the dictionary,

# Dictionary of strings and ints
word_freq = {"Hello": 56,
             "at": 23,
             "test": 43,
             "this": 43}


key = 'at'
value = 100

# If key does not exist in dictionary then add new pair
if key not in word_freq:
    word_freq.update({key: value})
else:
    print('Key already exist')

print(word_freq)

Output:

Key already exist
{'Hello': 56,
 'at': 23,
 'test': 43,
 'this': 43}

As key ‘at’ was already present in the dictionary, it did not add it.

Function to add key-value pair only if Key does not exist in the dictionary

Using above mentioned techinque, we can insert key-value pair only when Key does not exist in the dictionary. But if we want to add several key-value pairs, it is not practical to write if-else checks for every Key. So, let’s create a function for the same, which will make our life litlle easy. For example,

def add_if_key_not_exist(dict_obj, key, value):
    """ Add new key-value pair to dictionary only if
    key does not exist in dictionary. """
    result = False
    if key not in dict_obj:
        word_freq.update({key: value})
        result = True

    if not result:
        print('Key - ', key, ' - already exists in the dictionary')



# Dictionary of strings and ints
word_freq = {"Hello": 56,
             "at": 23,
             "test": 43,
             "this": 43}

add_if_key_not_exist(word_freq, 'at', 20)
add_if_key_not_exist(word_freq, 'how', 23)

print(word_freq)

Output:

Key -  at  - already exists in the dictionary

{'Hello': 56,
 'at': 23,
 'test': 43,
 'this': 43,
 'how': 23}

Here, we added multiple key-value pairs to the dictionary only if key does not exist in the dictionary.

Summary:

Today we learned how to add key-value pairs to the dictionary only when the given key does not exist.

Advertisements

Leave a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top