A dictionary in Python is a collection of key-value pairs, where each key maps to a specific value.
Dictionaries are:
- Unordered (no fixed position)
- Mutable (can be changed)
- Indexed by keys (not by position)
- Fast for lookups (use hashing internally)
person = {
"name": "John",
"age": 30,
"city": "New York"
}Keys must be unique and immutable (like strings, numbers, or tuples).
Values can be of any data type — even lists or other dictionaries.
empty_dict = {}
print(empty_dict)Output:
{}
person = {
"name": "John",
"age": 30,
"city": "New York"
}
print(person)Output:
{'name': 'John', 'age': 30, 'city': 'New York'}
Access values using keys or the safer get() method.
print(person["name"]) # Direct access
print(person.get("age")) # Using get()
print(person.get("gender", "Not specified")) # Default value if key missingOutput:
John
30
Not specified
person["gender"] = "Male"
print(person)Output:
{'name': 'John', 'age': 30, 'city': 'New York', 'gender': 'Male'}
person["age"] = 31
print(person)Output:
{'name': 'John', 'age': 31, 'city': 'New York', 'gender': 'Male'}
del person["city"]
print(person)Output:
{'name': 'John', 'age': 31, 'gender': 'Male'}
| Method | Description | Example | Output |
|---|---|---|---|
keys() |
Returns all keys | person.keys() |
dict_keys(['name', 'age', 'gender']) |
values() |
Returns all values | person.values() |
dict_values(['John', 31, 'Male']) |
items() |
Returns key-value pairs as tuples | person.items() |
dict_items([('name', 'John'), ('age', 31), ('gender', 'Male')]) |
pop(key) |
Removes the key and returns its value | person.pop('age') |
31 |
update() |
Updates dictionary with another dictionary | person.update({'city': 'SF'}) |
Merged result |
person.update({"age": 32, "city": "San Francisco"})
print(person)Output:
{'name': 'John', 'gender': 'Male', 'age': 32, 'city': 'San Francisco'}
Dictionaries allow keys and values of different types.
my_dict = {
1: "one",
"two": 2,
(3, 4): [1, 2, 3],
"nested_dict": {"a": 1, "b": 2}
}Accessing Values:
print(my_dict[1])
print(my_dict["two"])
print(my_dict[(3, 4)])
print(my_dict["nested_dict"]["a"])Output:
one
2
[1, 2, 3]
1
student_scores = {
"Alice": [85, 90, 92],
"Bob": (88, 79, 95),
"Charlie": [78, 81, 85]
}
print(student_scores["Alice"])
print(student_scores["Bob"][1])Output:
[85, 90, 92]
79
Since tuples are immutable, they can be dictionary keys.
coordinates = {
(0, 0): "Origin",
(1, 2): "Point A",
(3, 4): "Point B"
}
print(coordinates[(1, 2)])Output:
Point A
for key in person:
print(key)
for value in person.values():
print(value)
for key, value in person.items():
print(f"{key}: {value}")Output (order may vary):
name
gender
age
city
John
Male
32
San Francisco
name: John
gender: Male
age: 32
city: San Francisco
Compact way to create dictionaries.
squares = {x: x**2 for x in range(1, 6)}
print(squares)Output:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Dictionaries can contain other dictionaries.
students = {
"Alice": {"age": 24, "grade": "A"},
"Bob": {"age": 22, "grade": "B"},
"Charlie": {"age": 23, "grade": "C"}
}
print(students["Alice"]["age"])
print(students["Charlie"]["grade"])Output:
24
C
Adds the key with a default value if it doesn’t exist.
person.setdefault("nationality", "Unknown")
print(person)Output:
{'name': 'John', 'gender': 'Male', 'age': 32, 'city': 'San Francisco', 'nationality': 'Unknown'}
| Error | Cause | Example |
|---|---|---|
KeyError |
Accessing a non-existent key directly | person["salary"] |
TypeError |
Using a mutable object as a key | {[1,2]: "list"} |
AttributeError |
Using non-existent methods | person.append("age") |
| Concept | Description |
|---|---|
| Key-Value Pair | Maps unique keys to values |
| Mutable | Can add, remove, or modify items |
| Unordered | Keys are not stored in order (before Python 3.7) |
| Hashable Keys | Keys must be immutable (string, number, tuple) |
| Supports Nesting | Dictionaries can hold other dictionaries |
| Useful Methods | keys(), values(), items(), pop(), update(), setdefault() |
- Create a dictionary to store student names and their grades, then print all students with grade “A”.
- Merge two dictionaries using
.update()and print the result. - Use a dictionary comprehension to map numbers (1–5) to their cubes.
- Create a nested dictionary for three employees containing their name, department, and salary.
- Try accessing a missing key using both
[]and.get()— note the difference.