A dictionary (dict) stores key-value pairs. These show up everywhere in real Python code, and you'll meet them again immediately once you reach working with databases.
student = {
"name": "Priya",
"age": 21,
"course": "Web Development",
}
print(student["name"]) # "Priya"student["email"] = "priya@example.com" # adds a new key
student["age"] = 22 # overwrites an existing one
del student["email"] # removes a keyfor key, value in student.items():
print(f"{key}: {value}")
# name: Priya
# age: 21
# course: Web DevelopmentReading a missing key with [ ] raises a KeyError and stops the script — .get() returns None (or a fallback you choose) instead, which is usually what you actually want:
email = student.get("email") # None — key doesn't exist, no crash
email = student.get("email", "no email") # "no email" — a custom fallbackCombining lists and dictionaries models real-world data naturally — this shape will look familiar once you reach the Python-and-Databases lesson, since a database row often lands in Python exactly this way:
students = [
{"name": "Priya", "age": 21},
{"name": "Amit", "age": 23},
]
print(students[0]["name"]) # "Priya"| Method | What it does |
|---|---|
| d.keys() | All the keys |
| d.values() | All the values |
| d.pop(key) | Removes a key and returns its value |
| d.update(other) | Merges another dictionary in, overwriting any matching keys |
a = {"name": "Priya", "age": 21}
b = {"age": 22, "course": "Web Development"}
a.update(b)
print(a) # {'name': 'Priya', 'age': 22, 'course': 'Web Development'}