Python Dictionaries
A dictionary in Python is a powerful data structure used to store data in key–value pairs.
Dictionaries are optimized for fast lookup, making them one of the most important and widely used data types in Python.
This topic covers dictionaries from basics to practical usage.
What Is a Dictionary?
A dictionary:
- Stores data as key : value pairs
- Is mutable
- Does not allow duplicate keys
- Allows mixed data types
- Provides fast access using keys
python
student = {
"name": "Jayesh",
"age": 25,
"course": "Python"
}
print(student)
Dictionary vs List vs Tuple vs Set
| Feature | List | Tuple | Set | Dictionary |
|---|---|---|---|---|
| Ordered | Yes | Yes | No | Yes (Python 3.7+) |
| Mutable | Yes | No | Yes | Yes |
| Duplicates | Yes | Yes | No | Keys: No |
| Access | Index | Index | No | Key |
| Structure | Values | Values | Values | Key–Value |
Creating Dictionaries
Using Curly Braces {}
python
person = {"name": "Amit", "age": 30}
print(person)
Using dict() Constructor
python
person = dict(name="Amit", age=30)
print(person)
python
pairs = [("a", 1), ("b", 2)]
d = dict(pairs)
print(d)
Access Dictionary Items
Using Key
python
print(person["name"])
Using get() (Safe Access)
python
print(person.get("age"))
print(person.get("salary")) # None
Dictionary Keys and Values
Keys Must Be Immutable
python
d = {(1, 2): "value"}
print(d)
Invalid:
python
# d = {[1, 2]: "value"} # TypeError
Values Can Be Any Data Type
python
data = {
"id": 1,
"skills": ["Python", "AWS"],
"active": True
}
Change Dictionary Items
python
person["age"] = 31
print(person)
Add New Items
python
person["city"] = "Pune"
print(person)
Remove Dictionary Items
pop()
python
person.pop("age")
print(person)
del
python
del person["city"]
clear()
python
person.clear()
Loop Through Dictionary
Loop Through Keys
python
for key in person:
print(key)
Loop Through Values
python
for value in person.values():
print(value)
Loop Through Key–Value Pairs
python
for key, value in person.items():
print(key, value)
Check If Key Exists
python
if "name" in person:
print("Key exists")
Dictionary Length
python
print(len(person))
Nested Dictionaries
python
students = {
"student1": {"name": "A", "age": 20},
"student2": {"name": "B", "age": 22}
}
print(students["student1"]["name"])
Copy a Dictionary
python
copy_dict = person.copy()
print(copy_dict)
Merge Dictionaries
python
a = {"x": 1}
b = {"y": 2}
c = a | b
print(c)
python
a.update(b)
print(a)
Dictionary Comprehension
python
numbers = [1, 2, 3]
squares = {x: x*x for x in numbers}
print(squares)
When to Use Dictionaries
Use dictionaries when:
- Data has a meaningful key
- Fast lookup is required
- Data is structured
- Representing real-world objects
Common Mistakes
Accessing Missing Key Directly
python
# print(person["salary"]) # KeyError
Use
get() instead.Summary
- Dictionaries store key–value pairs
- Keys must be immutable and unique
- Fast lookup performance
- Mutable and dynamic
- Support nesting and comprehension
- Essential for real-world Python applications