Dictionaries

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.

Python

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:

Python

Let's update our dictionary with the new information about Bob:

Python
Output

Another way to add new information to an existing dictionary is by using the dict.update() method:

Python
Output

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:

Python
Output

We have added Bob's gender and his job at the same time.


What will be the output?

Python

What will be the output?

Python

What will be the output?

Python

Back to Bob.

Python

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:

Python
Output

dict.update() can also update a key-value pair:

Python
Output

That's because the dictionary that you pass as argument to dict.update() takes precedence over the existing one.


What will be the output?

Python

What will be the output?

Python

Awesome. Now we just need to learn how to delete existing key-value pairs.

Key-value pairs can be deleted using the del keyword:

Python
Output

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:

Python
Output

What will be the output?

Python

What will be the output?

Python