A dictionary (dict) stores key: value pairs. It is ordered (by insertion), changeable, and keys must be unique.
student = {"name": "Asha", "age": 21, "course": "BCA"}
Access
student["name"]—KeyErrorif missingstudent.get("phone")→None;get("phone", "N/A")with a default"age" in student— check a key
Add, change, delete
student["city"] = "Patna"— add or updateupdate({...})— several at oncepop("age"),del student["age"],popitem(),clear()setdefault(key, default)
Loop
for key in d:for value in d.values():for key, value in d.items():
Nested dictionaries
Values can be lists or other dicts — this is how JSON data looks in Python.
Helpers
dict.fromkeys(keys, 0)merged = a | b(Python 3.9+)collections.Counter— count itemscollections.defaultdict— automatic default values
Keys must be immutable: strings, numbers or tuples.
Example
Example — Student records
Python
from collections import Counter
student = {"name": "Asha", "age": 21, "marks": {"math": 88, "physics": 76}}
print(student["name"], student.get("phone", "N/A"))
student["city"] = "Patna"
student["marks"]["chemistry"] = 91
for subject, mark in student["marks"].items():
print(f"{subject:<10}{mark}")
total = sum(student["marks"].values())
print("Total:", total)
words = "to be or not to be".split()
print(Counter(words).most_common(2))
defaults = {"theme": "light", "lang": "en"}
user = {"lang": "hi"}
print(defaults | user)
Prints Asha N/A, a table of subjects and marks including chemistry 91, Total: 255, [('to', 2), ('be', 2)], and {'theme': 'light', 'lang': 'hi'} — the user's value wins when merging.