Dict basics
- Python course
- Beginner
- Lesson 67/116
- 5 min
Learn key-value mapping with {k: v}.
Dict basics
A dict (dictionary) is an ordered collection of key-value pairs. It uses curly braces and a colon:
person = {"name": "Alex", "age": 28}
print(person["name"]) # AlexA dict maps a key to a value. Keys must be unique; values can be any type. Access is done by key indexing.
Since Python 3.7, a dict keeps its insertion order. This makes loop order stable.
Dict access and assignment
Adding a new key to a dict is done by assignment; querying a missing key raises KeyError:
person = {"name": "Alex"}
person["age"] = 28 # adds a new key
print(person["age"]) # 28
print(person["city"]) # KeyErrorTo return a default for missing keys, use .get(); this method is safe.
Practice Print dict elements
Assign the dict {"name": "Ayse", "age": 28} to person. Assign person["name"] to name and person["age"] to age. Then print print(name, age).
Starter code
# Define a person with a dictSample solution
person = {"name": "Ayse", "age": 28}
name = person["name"]
age = person["age"]
print(name, age)Expected output
Ayse 28
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which is a valid dict?
- {"a": 1} Correct answer
- ("a": 1)
- <"a": 1>
- ["a": 1]
Explanation: {"a": 1} with curly braces is a dict.
2 Match the dict concepts
| Term | Meaning |
|---|---|
{"k": v} |
Dict syntax |
key |
Key |
value |
Value |
person["name"] |
Access |
3 Access a dict element
person = {"name": "Ayse"}
print(person[____])
person = {"name": "Ayse"}
print(person["name"])
Explanation: person["name"] gives the value.