Python program to append/add or update key/value pairs in a dictionary

Introduction :

In this tutorial, we will learn how to append or update or add a new key/value pairs in a dictionary in python. Python dictionary holds key-value pairs and curly braces are used for it. Using a key, we can access the value associated with it. Python provides one method called update for dictionaries that we can use to update or add new key-value pairs. In this tutorial, I will show you couple of different ways to use update() with examples :

Definition of update :

update method is defined as below :

dic.update(iterable)

It takes one iterable object of key-value pairs or a dictionary. It updates the caller dictionary using the provided values. It doesn’t return anything or return None.

Example 1: Update the value of an existing key :

The below example will update the value of an existing key of a python dictionary.

given_dict = {'sun': 1, 'mon' : 2, 'tues' : 3}

given_dict.update({'mon' : 3})
print(given_dict)

given_dict.update(mon = 4)
print(given_dict)

Here, givendict_ is the given python dictionary. We are updating this dictionary two times. We are updating the value of mon in both update statements. Both are different ways to update a dictionary. It will print the below output :

{'sun': 1, 'mon': 3, 'tues': 3}
{'sun': 1, 'mon': 4, 'tues': 3}

Example 2: Update multiple values of different keys :

Similar to the above example, we can also update multiple values in a dictionary using update :

given_dict = {'sun': 1, 'mon' : 2, 'tues' : 3}

given_dict.update([('sun', 10), ('mon', 20), ('tues', 30)])
print(given_dict)

Here we are passing one list of tuples. It will update the values of all keys :

{'sun': 10, 'mon': 20, 'tues': 30}

Example 3: Append one or multiple key-value pairs to a dictionary :

We can pass one dictionary or list of tuples to update method. If the list of tuples is new, or if the keys doesn’t exist in the dictionary, it will append these pairs to the dictionary.

given_dict = {'sun': 1, 'mon' : 2, 'tues' : 3}

given_dict.update([('wed', 4), ('thurs', 5), ('fri', 6), ('sat', 7)])
print(given_dict)

Here, we are passing one tuple to the update method and all are new to the dictionary. So, it will append these to the existing elements. It will print :

{'sun': 1, 'mon': 2, 'tues': 3, 'wed': 4, 'thurs': 5, 'fri': 6, 'sat': 7}

Example 4: Apppend one new dictionary :

If you pass one new dictionary to update:

given_dict = {'sun': 1, 'mon' : 2, 'tues' : 3}

given_dict.update({'wed': 4, 'thurs' : 5, 'fri' : 6, 'sat' : 7})
print(given_dict)

It will append them all :

{'sun': 1, 'mon': 2, 'tues': 3, 'wed': 4, 'thurs': 5, 'fri': 6, 'sat': 7}

And, if you pass a dictionary with existing values :

given_dict = {'sun': 1, 'mon' : 2, 'tues' : 3}

given_dict.update({'sun': 4, 'mon' : 5, 'tues' : 6})
print(given_dict)

It will update the values :

{'sun': 4, 'mon': 5, 'tues': 6}

You might also like: