Data StructuresPython Dictionaries
A dictionary is an ordered, mutable collection that stores data as key-value pairs. Instead of accessing items by a numeric index like lists, you access them by a meaningful key — a word, a string, a number.
Think of a real dictionary: you look up a word (the key) to find its definition (the value). Python dictionaries work exactly the same way. They are one of the most powerful and frequently used data structures in all of Python.
Creating a Dictionary
Dictionaries are created using curly braces with key-value pairs separated by colons. Keys must be unique and immutable (strings, numbers, tuples). Values can be anything.
person = {
"name": "Alice",
"age": 30,
"city": "Accra",
"is_active": True
}
print(person)
print(type(person))
print(len(person))
Output{'name': 'Alice', 'age': 30, 'city': 'Accra', 'is_active': True}
<class 'dict'>
4
Accessing Values
Access a value by placing its key inside square brackets. Alternatively, use the .get() method — it is safer because it returns None instead of raising a KeyError when the key does not exist.
person = {"name": "Alice", "age": 30, "city": "Accra"}
# Square bracket access
print(person["name"])
print(person["age"])
# .get() — safe access with optional default
print(person.get("city"))
print(person.get("email")) # Key doesn't exist → None
print(person.get("email", "N/A")) # Key doesn't exist → default value
OutputAlice
30
Accra
None
N/A
Adding and Changing Items
To add a new key-value pair, assign to a key that does not yet exist. To change an existing value, assign to a key that already exists. Both use the same syntax.
profile = {"username": "alice99", "level": 1}
# Add a new key
profile["email"] = "alice@example.com"
print(profile)
# Change an existing value
profile["level"] = 5
print(profile)
# .update() — add or change multiple keys at once
profile.update({"level": 10, "badge": "gold"})
print(profile)
Output{'username': 'alice99', 'level': 1, 'email': 'alice@example.com'}
{'username': 'alice99', 'level': 5, 'email': 'alice@example.com'}
{'username': 'alice99', 'level': 10, 'email': 'alice@example.com', 'badge': 'gold'}
Removing Items
Python gives you several ways to remove key-value pairs from a dictionary, each with slightly different behaviour.
config = {"host": "localhost", "port": 5432, "debug": True, "version": "1.0"}
# .pop(key) — removes and returns the value
port = config.pop("port")
print(f"Removed port: {port}")
print(config)
# del — removes by key, returns nothing
del config["debug"]
print(config)
# .popitem() — removes and returns the last inserted pair
last = config.popitem()
print(f"Removed last item: {last}")
print(config)
OutputRemoved port: 5432
{'host': 'localhost', 'debug': True, 'version': '1.0'}
{'host': 'localhost', 'version': '1.0'}
Removed last item: ('version', '1.0')
{'host': 'localhost'}
Looping Through a Dictionary
You can loop through a dictionary's keys, values, or both simultaneously using the built-in .keys(), .values(), and .items() methods.
student = {"name": "Bob", "grade": "A", "score": 94}
# Loop through keys
for key in student.keys():
print(key)
print("---")
# Loop through values
for value in student.values():
print(value)
print("---")
# Loop through key-value pairs
for key, value in student.items():
print(f"{key}: {value}")
Outputname
grade
score
---
Bob
A
94
---
name: Bob
grade: A
score: 94
Checking if a Key Exists
Use the in keyword to check whether a key exists in a dictionary before accessing it. This prevents KeyError crashes in your programs.
user = {"name": "Alice", "role": "admin"}
if "role" in user:
print(f"User role: {user['role']}")
if "email" not in user:
print("No email on file — please update your profile.")
OutputUser role: admin
No email on file — please update your profile.
Nested Dictionaries
A dictionary can contain other dictionaries as values. This is called a nested dictionary and is the standard way to represent structured, hierarchical data — like a user database or an API response.
users = {
"user_1": {"name": "Alice", "age": 30, "role": "admin"},
"user_2": {"name": "Bob", "age": 25, "role": "viewer"},
"user_3": {"name": "Charlie", "age": 28, "role": "editor"}
}
# Access nested values
print(users["user_1"]["name"])
print(users["user_2"]["role"])
# Loop through nested dict
for user_id, info in users.items():
print(f"{user_id}: {info['name']} ({info['role']})")
OutputAlice
viewer
user_1: Alice (admin)
user_2: Bob (viewer)
user_3: Charlie (editor)
💡Best Practice: Always use .get() instead of bracket access when you are not 100% certain a key exists. A missing key with bracket access crashes your program with a KeyError. .get() returns None or your chosen default — your program keeps running.