1. Altering dictionaries
In the prior video we learned that dictionaries are mutable, so we can alter them in a number of ways. Let's start by adding data to them. Which is something that you, as a data scientist, will need to do all the time.
2. Adding and extending dictionaries
You can add data to a dictionary just by using a new key as an index and assigning it a value. It's also possible to supply a dictionary, list of tuples or a set of keywords arguments to the update() method to add values into a dictionary. I have a dictionary that contains the art galleries in the 10007 zip code and I want to add it to my art_galleries dictionary. I assign the zip code as the key and then the dictionary as the value.
3. Updating a dictionary
I can also create a list of tuples, and supply them to the update() method. Here I'm supplying them to a dictionary index of the zip code since I want this data to be nested underneath it. Finally I'll print the zip code to be sure they were added. Notice how those are now a dictionary under that key. Often, We'll also want to narrow down our dataset to only the data which is relevant to the problem at hand, so let's learn how to remove data.
4. Popping and deleting from dictionaries
You can use the del python instruction on a dictionary key to remove data from a dictionary. However, it's important to remember that del will throw a KeyError if the key you are trying to delete does not exist. The pop() method provides a safe way to remove keys from a dictionary. Let's start by removing all the galleries from zipcode '11234', then I'm not sure if there are any galleries in zip code 10310, so I'm going to pop that zip code from the dictionary and save it. Finally, I'll print the popped value.
5. Let's practice!
Now let's go apply what we just learned in some exercises.