There's a few ways to values to a dictionary.
To add one value at a time to a dictionary, just set the dictionary's key with a new value.
The update(..)
command adds the dictionary in parentheses to the other dictionary.
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.
To "get back" a value you've stored in a dictionary, ask for it by its key:
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!"
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:
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: