In this article we will discuss how to add or append new key value pairs in a dictionary and also how to update value of existing keys.

Python dictionary provides a member function update() i.e.

It accepts in iterable sequence of key value pairs that can be single key value pair or list of tuples or an another dictionary. For each entry in sequence, it will add the given key value pair in dictionary and if key already exists then it will update its value.

Let’s use this to add new key value pairs in dictionary or updating existing one.

Suppose we have dictionary of string and int i.e.

Append a new key value pair in dictionary

It will add a new key value pair in the dictionary. Dictionary contents will be now

If key is string you can directly add without curly braces i.e.

Updating value of existing key in dictionary

If call the update() function with a key/value and key already exists in dictionary then its value will be updated by new value i.e

Key ‘Hello’ already exist in dictionary i.e.

Now let’s call update() on key ‘Hello’ i.e.

Now value of key ‘Hello’ will be updated and contents of dictionary will be,

Append multiple key value pair in dictionary

As update() accepts an iterable sequence of key value pairs, so we can pass a dictionary or list of tuples of new key value pairs to update(). It will all add the given key value pairs in the dictionary, if any key already exists then it will update its value.

Adding a list of tuples (key value pairs) in dictionary

Dictionary contents will be now,

Adding a dictionary to another dictionary

Suppose we have two dictionary i.e.

Let’s add the contents of dict2 in dict1 i.e.

Contents of dict1 will be now,

Complete example is as follows,

Output:

 

Click Here to Subscribe for more Articles / Tutorials like this.