Table of Contents
What Is a Dictionary in Python?
A dictionary in Python is a built-in data structure that stores data in key-value pairs. Since Python 3.7, dictionaries also maintain insertion order, making them even more reliable for data mapping and iteration.
For many Python developers—especially those writing quick scripts, prototypes, or data manipulation tools—dictionaries (dict
) are a go-to structure due to their simplicity and power.
my_dict = {
"name": "CIL",
"age": 1,
"site": "Blogger"
}
In this simple snippet, "name"
, "age"
, and "site"
are the keys, and their respective values are "CIL"
, 1
, and "Blogger"
.
Why I Use Dictionaries (a Lot)
Personally, I find dictionaries more comfortable than lists in many situations, particularly when I need to organize or access data quickly. Even when preparing data for insertion into a database, I often use dictionaries as an intermediate format. However, I’ve also learned to be cautious: sometimes a list or tuple might be more appropriate depending on the use case.
Key Benefits of Python Dictionaries
Fast Data Access
Dictionaries offer constant time complexity O(1) for retrieving values using keys, thanks to the underlying hash table mechanism.
Flexible Value Types
A dictionary can store strings, numbers, lists, other dictionaries—or any combination:
complex_dict = {
"user": "admin",
"roles": ["editor", "moderator"],
"metadata": {"last_login": "2025-05-24"}
}
Improved Readability
Key-value pairs convey semantic meaning, making your code easier to understand.
user["is_active"] = True # Meaningful and readable
Dynamic Modification
Add, remove, or update key-value pairs on the fly:
my_dict["email"] = "cil@blogger.com"
del my_dict["site"]
Limitations of Python Dictionaries
Higher Memory Consumption
Dictionaries use more memory than lists due to their hash-based storage model.
Key Constraints
Keys must be immutable and hashable, such as strings, integers, or tuples containing only hashable items.
No Manual Reordering
The order of keys follows insertion order, but you can’t directly sort or rearrange the order inside the dictionary itself without creating a new one.
No Duplicate Keys
Defining the same key twice will overwrite the previous value:
data = {"id": 1, "id": 2}
print(data) # {'id': 2}
Common Dictionary Operations in Python
Here’s a breakdown of common dictionary actions you should master:
# Create dictionary
my_dict = {"name": "CIL", "age": 1, "site": "Blogger"}
# Access
print(my_dict["name"]) # CIL
# Add or update
my_dict["email"] = "cil@blogger.com"
my_dict["age"] = 2
# Delete
del my_dict["site"]
# Looping
for key in my_dict:
print(key)
for value in my_dict.values():
print(value)
for key, value in my_dict.items():
print(f"{key}: {value}")
# Check if key exists
if "name" in my_dict:
print("Name in dictionary")
# Safe get with fallback
print(my_dict.get("major", "Undeclared"))
# Set default value if missing
graduation_year = my_dict.setdefault("graduation_year", 2024)
print(graduation_year)
Output Example
CIL
1
{'name': 'CIL', 'age': 2, 'email': 'cil@blogger.com'}
...
dict_items([('name', 'CIL'), ('age', 2), ('email', 'cil@blogger.com')])
Name in dictionary
Undeclared
2024
Real-World Example: Dictionary as a Lightweight Data Handler
In one of my past projects, I was analyzing word similarity in news headlines. Initially, I considered using tensors with libraries like PyTorch or TensorFlow to handle vectorized data. But the application became too memory-intensive.
I reverted to Python dictionaries to mimic tensor-like behavior. It allowed quick lookup and data pairing. However, I later realized that while dictionaries were flexible, they consumed too much memory, contributing to performance issues.
This experience reminded me to weigh the trade-offs—especially when scalability and efficiency matter.
When Not to Use Dictionaries
Sometimes simpler structures—like lists or tuples—are more appropriate, particularly when:
- The order of elements matters and keys aren’t needed
- Data is homogeneous (e.g., list of scores or timestamps)
- Memory is constrained
Avoid overengineering by reaching for dictionaries only when key-value mapping is actually necessary.
Final Thoughts
Dictionaries are an indispensable part of the Python developer’s toolbox in 2025. Whether you’re building REST APIs, working with JSON, handling configuration files, or managing user sessions, dictionaries provide a fast, readable, and dynamic way to store and access data.
That said, it’s worth taking a moment before defaulting to a dict
. Ask yourself:
Do I really need keys, or will a list or tuple do the job more efficiently?
By thinking critically about data structure choices, you’ll write cleaner, faster, and more maintainable Python code.
Common Error and Fix
1. KeyError
Cause: Trying to access a key that doesn’t exist.
Example:
data = {"name": "Alice"}
print(data["age"]) # KeyError: 'age'
Fix:
- Use
in
to check if the key exists - Use
.get()
to avoid the error
if "age" in data:
print(data["age"])
# or
print(data.get("age", "default value")) # "default value"
2. TypeError: unhashable type
Cause: Using a mutable object (like list or dict) as a dictionary key
Example:
my_dict = {[1, 2]: "value"} # TypeError
Fix:
- Use only immutable types like
str
,int
, ortuple
as keys
my_dict = {(1, 2): "value"} # OK
3. AttributeError: 'dict' object has no attribute ...
Cause: Trying to use dot notation on a dictionary
Example:
data = {"name": "Bob"}
print(data.name) # AttributeError
Fix:
- Use square bracket access instead
print(data["name"]) # OK
4. ValueError
(when converting to dict)
Cause: Trying to convert a structure to a dict incorrectly
Example:
dict([1, 2, 3]) # ValueError
Fix:
- Provide key-value pairs as tuples
dict([("a", 1), ("b", 2)]) # OK
5. RuntimeError: dictionary changed size during iteration
Cause: Modifying a dictionary while iterating over it
Example:
my_dict = {"a": 1, "b": 2}
for k in my_dict:
my_dict["c"] = 3 # RuntimeError
Fix:
- Iterate over a copy of the keys
for k in list(my_dict):
my_dict["c"] = 3
6. Nested dictionary access errors
Cause: Accessing a key in a nested dictionary when it doesn’t exist
Example:
data = {"user": {}}
print(data["user"]["name"]) # KeyError
Fix:
- Use
.get()
with default values
name = data.get("user", {}).get("name", "Unknown")
Bonus Tip: Use defaultdict
Problem:
d = {}
d["x"] += 1 # KeyError
Fix:
from collections import defaultdict
d = defaultdict(int)
d["x"] += 1 # OK