Image by Author
In Python, the dictionary is a useful built-in data structure that lets you define a mapping between elements as key-value pairs. You can use the key to retrieve the corresponding values. And you can always update one or more keys of the dictionary.
To do so, you can use for loops or the built-in dictionary update()
method. In this guide, you will learn both of these methods.
Consider the following dictionary books
:
books = {'Fluent Python':50,
'Learning Python':58}
In the above dictionary, the names of the books (popular Python programming books) are the keys and the prices in USD are the values. Note that the books
dictionary has been created for this tutorial, and the prices in USD don’t correspond to the exact prices. :)
Now consider another dictionary more_books
:
more_books = {'Effective Python':40,
'Think Python':29}
Image by Author
Suppose you’d like to update the books
dictionary with key-value pairs from the more_books
dictionary. You can do it using a for loop as follows:
- loop through the keys of the
more_books
dictionary and access the value, and - update the
books
dictionary adding the key-value pair to it.
for book in more_books.keys():
books[book] = more_books[book]
print(books)
We see that the books
dictionary has been updated to include the contents of the more_books
dictionary.
{
"Fluent Python": 50,
"Learning Python": 58,
"Effective Python": 40,
"Think Python": 29,
}
You can also use the items()
method on the more_books
dictionary to get all the key-value pairs, loop through them, and update the books
dictionary:
for book, price in more_books.items():
books[book] = price
print(books)
{
"Fluent Python": 50,
"Learning Python": 58,
"Effective Python": 40,
"Think Python": 29,
}
The general syntax to use the update()
dictionary method is as follows:
dict.update(iterable)
Here:
dict
is the Python dictionary that you would like to update, anditerable
refers to any Python iterable containing key-value pairs. This can be another Python dictionary or other iterables such as lists and tuples. Each item in the list or tuple should contain two elements: one for the key and one for the value.
Now let us reinitialize the books
and the more_books
dictionaries:
books = {'Fluent Python':50,
'Learning Python':58}
more_books = {'Effective Python':40,
'Think Python':29}
To update the books dictionary, you can call the update()
method on the books dictionary and pass in more_books
, as shown:
books.update(more_books)
print(books)
We see that the books
dictionary has been updated to include the contents of the more_books
dictionary as well. This method keeps your code maintainable.
{
"Fluent Python": 50,
"Learning Python": 58,
"Effective Python": 40,
"Think Python": 29,
}
Note: The
update()
method updates the original dictionary in place. In general, Usingdict1.update(dict2)
updates the dictionarydict1
(in place) and does not return a new dictionary. Theupdate()
method call, therefore, has a return type of None.
Updating a Python Dictionary With Contents From Other Iterables
Next, let's see how to add how to update a Python dictionary with elements from another iterable that is not a dictionary. We have the books and their prices as a list of tuples some_more_books
as shown. In each tuple, the element at index 0 denotes the key and the element at index 1 corresponds to the value.
some_more_books = [('Python Cookbook',33),('Python Crash Course',41)]
Image by Author
You can use the update()
method on the books
dictionary as before.
books.update(some_more_books)
print(books)
We see that the books
dictionary has been updated as expected.
{
"Fluent Python": 50,
"Learning Python": 58,
"Effective Python": 40,
"Think Python": 29,
"Python Cookbook": 33,
"Python Crash Course": 41,
}
Updating a Dictionary in the Presence of Repeating Keys
So far, you updated an existing Python dictionary with the key-value pairs from another dictionary and a list of tuples. In the example we considered, the two dictionaries did not have any keys in common.
What happens when there are one or more repeating keys? The value corresponding to the repeating key in the dictionary will be overwritten.
Let’s consider and_some_more
, a list containing tuples of key-value pairs. Notice that it contains ‘Fluent Python’, which is already present in the books
dictionary.
and_some_more = [('Fluent Python',45),('Python for Everybody',30)]
Image by Author
When you now call the update()
method on the books
dictionary and pass in and_some_more
, you will see that the value corresponding to the key ‘Fluent Python’ has now been updated to 45.
and_some_more = [('Fluent Python',45),('Python for Everybody',30)]
books.update(and_some_more)
print(books)
{
"Fluent Python": 45,
"Learning Python": 58,
"Effective Python": 40,
"Think Python": 29,
"Python Cookbook": 33,
"Python Crash Course": 41,
"Python for Everybody": 30,
}
In summary, Python's dictionary method update()
updates a Python dictionary with key-value pairs from another dictionary or another iterable. This method modifies the original dictionary, and has a return type of None. You can also use this method to merge two Python dictionaries. However, you cannot use this method if you want a new dictionary that has the contents of both the dictionaries.
Bala Priya C is a technical writer who enjoys creating long-form content. Her areas of interest include math, programming, and data science. She shares her learning with the developer community by authoring tutorials, how-to guides, and more.
No comments:
Post a Comment