Python Dictionaries: The Complete Guide with Real Examples
Open the contacts app on your phone. You look up a person by name and get their phone number. You don't search by position — you don't say "give me contact number 47." You search by name.
A Python dictionary works exactly like that. Instead of storing items by position (like a list), a dictionary stores items as key-value pairs. The key is the name you look up, and the value is what you get back.
Dictionaries are everywhere in real programming. User profiles, configuration settings, JSON data from APIs, word counters — they all use dictionaries. In this tutorial, you'll master every essential dictionary operation.
How to Create a Python Dictionary
You create a dictionary using curly braces {} with key-value pairs separated by colons. Each pair is separated by a comma.
Keys are usually strings, but they can be any immutable type — numbers, tuples, or booleans. Values can be anything — strings, numbers, lists, even other dictionaries.
Accessing and Modifying Dictionary Values
To get a value from a dictionary, put the key inside square brackets. To change a value, assign to that key. To add a new pair, just assign to a key that doesn't exist yet.
data = {'x': 10}
# Crashes with KeyError:
value = data['y']data = {'x': 10}
# Returns 0 if 'y' is missing:
value = data.get('y', 0)Essential Dictionary Methods
Dictionaries come with several built-in methods that make them easy to work with. Here are the ones you'll use most often.
Notice that update() both adds new keys and overwrites existing ones. In the example above, 'apples' changed from 5 to 10, and 'grapes' was added as a new key.
Looping Through Dictionaries
You can loop through a dictionary's keys, values, or both. The most common approach is to loop through items() so you get both the key and value at once.
Checking if a Key Exists
Before accessing a key, you often want to check if it exists first. The in keyword checks for keys — not values.
Nested Dictionaries
A dictionary value can be another dictionary. This is called nesting and it lets you represent complex, structured data — like a classroom of students, each with their own set of attributes.
To access a nested value, you chain square brackets: first the outer key, then the inner key. You can nest as deep as you want, but more than two or three levels gets hard to read.
Common Mistakes with Dictionaries
data = {'a': 1, 'b': 2, 'c': 3}
for key in data:
if data[key] < 2:
del data[key] # RuntimeError!data = {'a': 1, 'b': 2, 'c': 3}
for key in list(data.keys()):
if data[key] < 2:
del data[key] # Safe!
print(data) # {'b': 2, 'c': 3}Practice Exercises
Time to practice! These exercises progress from basic dictionary operations to more complex patterns.
Create a dictionary called pet with these key-value pairs:
'name': 'Buddy''species': 'dog''age': 5Then print the pet's name.
Expected output:
BuddyA dictionary representing a book is given. Do these steps in order:
1. Change the 'year' to 2024
2. Add a new key 'genre' with the value 'fiction'
3. Print the entire dictionary
Expected output:
{'title': 'The Great Adventure', 'author': 'Jane Smith', 'year': 2024, 'genre': 'fiction'}A user profile dictionary is given. Use the .get() method to safely print the user's phone number. If the key 'phone' doesn't exist, print 'No phone number'.
Expected output:
No phone numberLoop through the dictionary and print each fruit and its price in this format:
apple: $1.50
banana: $0.75
cherry: $3.00Make sure prices show exactly two decimal places.
Read this code carefully and predict what it will print. What happens when a dictionary has duplicate keys?
Type the exact output.
This code tries to check if the grade 'A' exists in the dictionary, but it's checking the wrong thing. Fix it so it prints:
Someone got an A!Count how many times each word appears in the given list. Store the counts in a dictionary called word_counts, then print it.
Expected output:
{'hello': 3, 'world': 2, 'python': 1}A nested dictionary of students is given. Loop through each student and print their name and math score in this format:
Alice: 95
Bob: 82
Charlie: 91Summary: What You Learned About Python Dictionaries
| Great work! Here's a recap of everything you now know: | ||
|---|---|---|
| --- | --- | --- |
| Create a dict | Store key-value pairs | d = {'name': 'Alice'} |
| Access by key | Get a value | d['name'] |
| Safe access | Default if missing | d.get('x', 0) |
| Add / modify | Set a value | d['age'] = 25 |
keys() | All keys | d.keys() |
values() | All values | d.values() |
items() | Key-value tuples | d.items() |
pop(key) | Remove and return | d.pop('age') |
update() | Merge dicts | d.update(other) |
in | Check if key exists | 'name' in d |
| Nesting | Dicts inside dicts | d['a']['b'] |
Dictionaries are one of the most important data structures in Python. JSON data, API responses, configuration files, counters — they all revolve around key-value pairs.
What's Next?
In the next tutorial — [Python Comprehensions](/python/python-comprehensions) — you'll learn how to create lists, dictionaries, and sets in a single elegant line of code.
Comprehensions let you replace multi-line loops with concise one-liners. They're one of the features that makes Python feel so clean and expressive.