Python Dictionaries
3 min read ·
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
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 {}
Using dict() Constructor
Access Dictionary Items
Using Key
Using get() (Safe Access)
Dictionary Keys and Values
Keys Must Be Immutable
Invalid:
Values Can Be Any Data Type
Change Dictionary Items
Add New Items
Remove Dictionary Items
pop()
del
clear()
Loop Through Dictionary
Loop Through Keys
Loop Through Values
Loop Through Key–Value Pairs
Check If Key Exists
Dictionary Length
Nested Dictionaries
Copy a Dictionary
Merge Dictionaries
Dictionary Comprehension
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
Use
get() instead.