Python Dictionaries: The Data Structure You'll Use Every Day
Learn how to use Python dictionaries effectively. This guide covers creating, accessing, updating, looping, and common methods every Python developer needs to know.
If I had to pick one Python data structure to teach a beginner first, it would be Python dictionaries. They map keys to values, they’re fast, and they show up everywhere — JSON data, function arguments, database rows, configuration. Understanding dictionaries deeply will make you a better Python developer.
Creating and Accessing Dictionaries
A dictionary is defined with curly braces and key-value pairs:
user = {
"name": "Kaikobud",
"age": 28,
"city": "Dhaka",
"skills": ["Python", "Go", "Docker"]
}
# Access by key
print(user["name"]) # Kaikobud
# Safe access with .get() — returns None if key doesn't exist
print(user.get("email")) # None
print(user.get("email", "not set")) # "not set"
Always prefer .get() when a key might not exist — accessing a missing key with user["email"] raises a KeyError.
Adding, Updating, and Removing Items
# Add a new key
user["email"] = "kai@kaiko.dev"
# Update an existing key
user["age"] = 29
# Remove a key
del user["city"]
# Remove and return a value
age = user.pop("age")
# Check if a key exists
if "email" in user:
print("Email found")
Looping Over Dictionaries
# Loop over keys (default)
for key in user:
print(key)
# Loop over values
for value in user.values():
print(value)
# Loop over key-value pairs — the most common pattern
for key, value in user.items():
print(f"{key}: {value}")
Dictionary Comprehensions
Just like list comprehensions, you can build dictionaries in one line:
numbers = [1, 2, 3, 4, 5]
squares = {n: n ** 2 for n in numbers}
# {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Conclusion
Python dictionaries are the backbone of data handling in Python. They’re used in API responses, function kwargs, configuration objects, and almost every non-trivial program. Get comfortable with .get(), .items(), and dictionary comprehensions — you’ll use all three constantly.
Read next: Python List Comprehensions: Write Less, Do More
External resource: Python Docs — Dictionaries
Related Articles
CSS Flexbox in Plain English: A Beginner's Guide
Learn CSS Flexbox with simple, visual explanations. This guide covers display flex, justify-content, align-items, flex-wrap, and practical layouts every developer needs to know.
Docker for Backend Developers: A Practical Introduction
Learn how Docker works, why backend developers need it, and how to containerize your first Python or Go application in under 30 minutes.
Environment Variables Explained: Keeping Secrets Out of Code
Learn what environment variables are and why every developer needs them. This guide covers how to use .env files, os.environ in Python, process.env in Node.js, and best practices.