Python Dictionaries – The Complete Guide for Beginners
Last updated 5 months, 1 week ago | 411 views 75 5

In Python, a dictionary is a powerful, flexible, and widely-used data structure that allows you to store data in key-value pairs.
In this tutorial, you’ll learn:
-
What dictionaries are
-
How to create and access them
-
Common methods and operations
-
Nesting dictionaries
-
Tips and pitfalls
What Is a Dictionary?
A dictionary in Python:
-
Stores data in key-value pairs
-
Is unordered (in versions <3.7)
-
Is mutable
-
Keys must be unique and immutable
-
Values can be of any type
Example:
person = {
"name": "Alice",
"age": 30,
"is_active": True
}
✅ Creating Dictionaries
Using Curly Braces
user = {"username": "john_doe", "email": "[email protected]"}
Using the dict()
Constructor
user = dict(username="john_doe", email="[email protected]")
Creating Empty Dictionary
empty_dict = {}
Accessing Dictionary Values
print(user["username"]) # john_doe
Using get()
to Avoid KeyError
print(user.get("email")) # [email protected]
print(user.get("phone", "N/A")) # N/A
✏️ Modifying Dictionaries
Add or Update a Key
user["age"] = 25 # Adds if not exists, updates if exists
Remove Items
del user["email"] # Deletes key
user.pop("age") # Removes and returns value
user.clear() # Empties the dictionary
Looping Through Dictionaries
Loop Through Keys
for key in user:
print(key, user[key])
Loop Through Values
for value in user.values():
print(value)
Loop Through Key-Value Pairs
for key, value in user.items():
print(f"{key}: {value}")
Common Dictionary Methods
Method | Description | Example |
---|---|---|
get(key) |
Get value by key | d.get("name") |
keys() |
Returns list of keys | d.keys() |
values() |
Returns list of values | d.values() |
items() |
Returns list of (key, value) pairs | d.items() |
pop(key) |
Removes specified key | d.pop("age") |
clear() |
Empties the dictionary | d.clear() |
update(dict2) |
Merges another dictionary | d.update({"city": "London"}) |
copy() |
Returns a shallow copy | d.copy() |
Nested Dictionaries
Dictionaries can contain other dictionaries.
student = {
"name": "Tom",
"grades": {
"math": 90,
"science": 85
}
}
print(student["grades"]["science"]) # 85
Dictionary Comprehensions
You can create dictionaries using a concise syntax:
squares = {x: x**2 for x in range(5)}
print(squares) # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
Full Example: Contact Book
contacts = {}
# Add new contact
contacts["Alice"] = {"phone": "123-456-7890", "email": "[email protected]"}
contacts["Bob"] = {"phone": "555-555-5555", "email": "[email protected]"}
# Access
print("Alice's email:", contacts["Alice"]["email"])
# Update
contacts["Bob"]["phone"] = "000-000-0000"
# Remove
del contacts["Alice"]
# Display
for name, info in contacts.items():
print(f"{name}: {info}")
Tips for Working with Dictionaries
-
Use
get()
to prevent crashes from missing keys. -
Use dictionary comprehension for dynamic dictionary creation.
-
Keys must be immutable (e.g., strings, numbers, tuples).
-
Use
update()
to merge two dictionaries.
⚠️ Common Pitfalls
Pitfall | Why It Happens | Fix |
---|---|---|
Accessing missing key | Raises KeyError |
Use get() with default |
Using mutable key (e.g., list) | Not allowed; keys must be hashable | Use tuples instead |
Modifying while iterating | Can cause unexpected behavior | Use .copy() or store keys first |
Confusing dict() syntax |
dict(name="John") ≠ {"name": "John"} |
Be mindful of keyword args |
Summary
Feature | Description |
---|---|
Data type | dict |
Key type | Immutable (str, int, tuple) |
Value type | Any (can be nested) |
Order preserved? | ✅ Yes (from Python 3.7+) |
Use cases | Fast lookup, mappings, configurations |
✅ Practice Exercise
Task: Create a program that counts the frequency of each word in a sentence.
sentence = "python is fun and python is easy"
words = sentence.split()
word_count = {}
for word in words:
word_count[word] = word_count.get(word, 0) + 1
print(word_count)
Output:
{'python': 2, 'is': 2, 'fun': 1, 'and': 1, 'easy': 1}
What’s Next?
After mastering dictionaries, dive into:
-
JSON and dictionary parsing
-
Handling nested data structures
-
Real-world examples like API responses and config files