~ Dictionaries


Adding to a dictionary

There's a few ways to values to a dictionary.

Adding values one at a time

To add one value at a time to a dictionary, just set the dictionary's key with a new value.

Merging two dictionaries

The update(..) command adds the dictionary in parentheses to the other dictionary.

Challenge

Create your own dictionary, perhaps mapping your favorite cities to their home countries, with at least 3 entries. Then, add one country:city pair with the update(..) function – the second way we talked about above – and another by creating a new key in the dictionary and setting its value – the first way we talked about.

Getting values from dictionaries

To "get back" a value you've stored in a dictionary, ask for it by its key:

Missing keys

If you ask for a key that doesn't exist, Python will return KeyError; that's its way fo telling you "sorry! Can't find what you were looking for!"

Looking up items by values

You'll get the same KeyError if you try to ask for something by its value rather than its key. This is because Python only looks at keys, not values:

Challenge

Take a look at the dictionary in the console. See if you can pull out all the names of the cities that start with the letter 'C' from the places dictionary: