A dictionary is a collection of key-value pairs.

Dictionaries are mutable meaning that items can be added or removed after they are created.

Basically, to add a single item to a dictionary we use the assignment syntax as in :

D[key] = value
cities = {}

cities['Moscow'] = 'Russia'
cities['Manilla'] = 'Philippines'
cities['Nairobi'] = 'Kenya'


In some cases, however, we may want to add multiple elements into a dictionary, such as from an existing collection of key-value pairs. This is where the update() method comes in.

Using the update() method

The update() method adds multiple items into a dictionary. The items can be from an existing dictionary or  from any other iterable of key-value pairs.

update() with another dictionary

If you have two dictionaries, to update one dictionary with the items from the other, you use the following syntax;


The distinct elements of dict_b will be added to dict_a 

D1 = {'Moscow': 'Russia', 'Nairobi': 'Kenya', 'Manilla': 'Philippines'}

D2 = {'Tokyo': 'Japan'}

#update D2 with items from d1

Dictionary keys are unique, this means that if the dictionary given as argument contain keys that are already present in the dictionary, the values associated with those keys will be overwritten with the incoming values.

d1 = {'a': 10, 'b': 20}
d2 = {'b':50, 'c':200}



update() with keyword arguments

You can pass keyword arguments to the update() method, as in  key = value. The syntax is as shown below;

dict.update(key1 = val1, key2 = val2, key3 = val3, ...)
d = {}

d.update(Moscow = 'Russia', Tokyo = 'Japan')


Note that with this approach, like in normal assignment, you do not have to enclose the keys with quotes, only the values.

update() with an iterable of key-value pairs

lastly, we can update a dictionary with items from an iterable of key-value pairs, as in [(key, value), (key, value), (key, value)]

d = {}

items = [('Beijing', 'China'), ('Ottawa', 'Canada')]



In the above example, we updated the dictionary with a list of two-length tuples, you can use any other form of iterable as long as it contains key-value pairs.

d = {}

values = ['one', 'two', 'three', 'four']



In the above example, we updated the dictionary using the index, value pairs generated by the builtin enumerate() function.