Dictionaries, explained simply
A real dictionary lets you look up a word to find its meaning. A Python dictionary works the same way: you look up a key to find its value.
You write a dictionary with curly brackets, putting a colon between each key and its value and commas between the pairs. To look something up, put the key in square brackets.
You can add a new pair or change an existing one by assigning to a key. If you ask for a key that is not there, Python raises a KeyError, so .get() is a safe way to look something up.
Example: A creature field guide
guide = {"owl": "night", "lark": "morning"}
print(guide["owl"])
guide["bat"] = "night"
print(len(guide))
print(guide.get("fox", "unknown"))Output
night
3
unknownTry this
- Make a dictionary of three friends and their favourite colours.
- Loop through a dictionary with for name in guide: and print each key and value.
- Change the value for one key and print the dictionary again.
