1. Create and access
A dictionary stores values under keys: it maps each key to one value. You write one with curly braces, a colon between each key and value, and commas between pairs:
- A key is usually a string or a number. Keys must be unique.
- A value can be any type: a number, a string, a list, another dictionary…
- If the same key appears twice in a literal, the last value wins.
Read a value with dictionary[key]:
The key must exist. If it does not, Python raises KeyError:
Dictionaries keep the insertion order, so printing one shows the pairs in the order they were added: {'name': 'Ada', 'age': 36}. Strings inside a dictionary are printed with single quotes.
Coming from JavaScript? A dict is an object or a Map, but keys can be any hashable value. A missing key raises KeyError instead of returning undefined.
Create and print a dictionary
Create a dictionary named person with the keys "name" and "age" and the values "Ada" and 36, using a dictionary literal. Then print the whole dictionary.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Read a value by key
Create person = {"name": "Ada", "age": 36}. Read the value stored under the key "name" with square brackets and print it.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Read a number
Create scores = {"math": 95, "science": 88}. Print the value stored under the key "math".
Print exactly:
Create a free account to save your progress and unlock chapter 2.
A repeated key keeps the last value
Keys are unique. Create config = {"theme": "light", "theme": "dark"} and print the dictionary. The second value for "theme" replaces the first.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Trigger a KeyError
Reading a key that is not in the dictionary raises KeyError and the program stops.
Create person = {"name": "Ada"} and print person["age"]. Running the code must stop with:
Create a free account to save your progress and unlock chapter 2.