Modifying Python Dictionaries
In this lesson, you will learn how to modify existing dictionaries by updating, adding, and deleting key-value pairs.
Let's create a new dictionary for a guy named Bob.
Now assume we learned that Bob is a data scientist and want to add this information to our dictionary.
New key-value pairs can be added to a dictionary through direct assignment, like so:
Let's update our dictionary with the new information about Bob:
Another way to add new information to an existing dictionary is by using the dict.update()
method:
Keep in mind that you should pass a separate dictionary as an argument to the dict.update()
method.
With dict.update()
, you can also add multiple key-value pairs at once:
We have added Bob's gender and his job at the same time.
What will be the output?
What will be the output?
What will be the output?
Back to Bob.
Let's assume that Bob just turned 31, and we need to update his age in our dictionary.
We can update a key-value pair in the same way as we add a new one, through direct assignment:
dict.update()
can also update a key-value pair:
That's because the dictionary that you pass as argument to dict.update()
takes precedence over the existing one.
What will be the output?
What will be the output?
Awesome. Now we just need to learn how to delete existing key-value pairs.
Key-value pairs can be deleted using the del
keyword:
You can also use the pop()
method, which we already know from its usage with strings and lists.
dict.pop(key)
removes the key-value pair associated with the specified key and returns the value:
What will be the output?
What will be the output?