Kodeclik Blog
How to update a Python dictionary
Recall that Python dictionaries are basically a list of (key, value) pairs.
Here is for instance a simple Python dictionary:
person = {'name': 'Tom', 'age': 30}
print(person)
The output will be:
{'name': 'Tom', 'age': 30}
Here the keys are ‘name’, and ‘age’. The values are ‘Tom’ and 30 respectively. Note that the keys are all strings but one value is a string and the other value is an integer.
Example 1: Updating a dictionary with another dictionary
The update() method is a very handy way - you apply it on one dictionary and pass it another dictionary as argument and the original dictionary (on which it is applied) is modified:
person = {'name': 'Tom', 'age': 30}
print(person)
person.update({'address': 'Boston', 'newage': 32})
print(person)
The output will be:
{'name': 'Tom', 'age': 30}
{'name': 'Tom', 'age': 30, 'address': 'Boston', 'newage': 32}
Note that the original dictionary had only two keys, namely name and age. After the updation, it has two additional keys, namely address and newage. Python has no way of knowing if you intended to update the date (did you?). Because you used a key ‘newage’ that is different from any existing key (like ‘age’), both keys are retained. If you would like to update the age, you should do:
person = {'name': 'Tom', 'age': 30}
print(person)
person.update({'address': 'Boston', 'age': 32})
print(person)
The output is now:
{'name': 'Tom', 'age': 30}
{'name': 'Tom', 'age': 32, 'address': 'Boston'}
Note that now there is only one key called ‘age’ which has been updated to 32.
Example 2: Updating a dictionary with key-value pairs
A second way to use the update() method is to pass key-value pairs rather than a dictionary. For instance, the last program above could very well have been written as:
person = {'name': 'Tom', 'age': 30}
print(person)
person.update(address='Boston', age=32)
print(person)
Note that now we assign values to keys using the “=” operator rather than a colon (“:”). Also note that the keys do not have enclosing quotes around them. Finally note that the argument to update is not a list or tuple but multiple arguments each having a key=value format.
This gives the same output as before:
{'name': 'Tom', 'age': 30}
{'name': 'Tom', 'age': 32, 'address': 'Boston'}
Example 3: Updating a dictionary with key-value iterable
A third way to use the update() method is to setup the new key, value pairs as an iterable:
person = {'name': 'Tom', 'age': 30}
print(person)
person.update([('address','Boston'), ('age',32)])
print(person)
Note that the quotes are back around the keys. This time we don’t have colons or even equal-to symbols between keys and values. Instead we have tuples of them packaged into a list which is then passed as the argument to the update() method.
The output is the same as before:
{'name': 'Tom', 'age': 30}
{'name': 'Tom', 'age': 32, 'address': 'Boston'}
Example 4: Shopping list
Imagine you have an e-commerce website where users can add products to their shopping cart. Each product has a name, price, and quantity. We can represent the shopping cart as a dictionary, where the keys are the product names, and the values are also dictionaries containing the price and quantity.
shopping_cart = {
"Apple": {"price": 0.5, "quantity": 2},
"Banana": {"price": 0.25, "quantity": 3},
"Orange": {"price": 0.75, "quantity": 1}
}
print(shopping_cart)
The output will be:
{'Apple': {'price': 0.5, 'quantity': 2},
'Banana': {'price': 0.25, 'quantity': 3},
'Orange': {'price': 0.75, 'quantity': 1}}
Now, let us say the user wants to add another item to their cart or update the quantity of an existing item. We can use the update() method to achieve this.
shopping_cart = {
"Apple": {"price": 0.5, "quantity": 2},
"Banana": {"price": 0.25, "quantity": 3},
"Orange": {"price": 0.75, "quantity": 1}
}
print(shopping_cart,end="\n\n")
shopping_cart.update({"Grapes": {"price": 1.25, "quantity": 2}})
print(shopping_cart)
The output of this updated program will be:
{'Apple': {'price': 0.5, 'quantity': 2},
'Banana': {'price': 0.25, 'quantity': 3},
'Orange': {'price': 0.75, 'quantity': 1}}
{'Apple': {'price': 0.5, 'quantity': 2},
'Banana': {'price': 0.25, 'quantity': 3},
'Orange': {'price': 0.75, 'quantity': 1},
'Grapes': {'price': 1.25, 'quantity': 2}}
Note that Grapes has been added to the shopping list.
Next, let us the quantity of an existing item ("Banana") by passing a dictionary with the same key but a different value for the "quantity" field. Here is a line for that:
shopping_cart.update({"Banana": {"price": 0.25, "quantity": 5}})
The final shopping cart will look like:
{'Apple': {'price': 0.5, 'quantity': 2},
'Banana': {'price': 0.25, 'quantity': 5},
'Orange': {'price': 0.75, 'quantity': 1},
'Grapes': {'price': 1.25, 'quantity': 2}}
Thus, the dictionary update method is very useful to maintain a dynamic data structure that can grow as new elements are added or if old elements are updated.
Note that the update() method is primarily used to add or modify key-value pairs in a dictionary. It cannot be used to delete existing pairs (only in so far as updating the value for a key to a new value, effectively replacing the old pair).
How dictionary.update() works internally
dictionary.update(x) is basically an efficient implementation of the for loop:
for key, value in x.items():
dictionary[key] = value
The advantage of using the update method (over doing the key-value assignment yourself) is that it can be used with functions that expect a function argument. For instance, the shopping cart program could be written as follows:
shopping_cart = {
"Apple": {"price": 0.5, "quantity": 2},
"Banana": {"price": 0.25, "quantity": 3},
"Orange": {"price": 0.75, "quantity": 1}
}
print(shopping_cart,end="\\n\\n")
def update_value(key, value, update_function):
update_function([(key, value)])
update_value("Grapes", {"price": 1.25, "quantity": 2},
shopping_cart.update)
update_value("Banana", {"price": 0.25, "quantity": 5},
shopping_cart.update)
print(shopping_cart)
Note that we have defined a Python function called update_value that takes three arguments: key, value, and update_function. The purpose of this function is to update a dictionary (any dictionary) by calling the provided update_function with a list containing a single key-value pair.
Once the function is defined, we call it two times. The first call adds a new key-value pair for "Grapes" to the shopping_cart dictionary, with a price of 1.25 and a quantity of 2. The second call updates the value associated with the "Banana" key in the shopping_cart dictionary, changing the quantity to 5 while keeping the price the same.
{'Apple': {'price': 0.5, 'quantity': 2},
'Banana': {'price': 0.25, 'quantity': 3},
'Orange': {'price': 0.75, 'quantity': 1}}
{'Apple': {'price': 0.5, 'quantity': 2},
'Banana': {'price': 0.25, 'quantity': 3},
'Orange': {'price': 0.75, 'quantity': 1},
'Grapes': {'price': 1.25, 'quantity': 2}}
In summary, the update() method updates the dictionary with the key-value pairs from either a provided dictionary, or an iterable of key-value pairs, or keyword arguments. If a key already exists in the dictionary, its value is updated; otherwise, a new key-value pair is added.
Finally, note that update() returns None, as it modifies the dictionary in-place.
If you would like to learn more about Python dictionaries, learn how to initialize dictionaries, how to append to a dictionary, how to increment a value in a dictionary, and even how to swap positions of values in a Python dictionary!
Also see our blogpost on implementing a shopping list in Python for a more systematic way to work with shopping lists!
Learn more about Python dictionaries by starting from our blogpost on how to initialize dictionaries.
Want to learn Python with us? Sign up for 1:1 or small group classes.