Dictionaries in Python
Dictionaries have been my favorite data structure throughout my 20 years as a software engineer. When I interviewed at Google, one of the problems I was…

Dictionaries have been my favorite data structure throughout my 20 years as a software engineer. When I interviewed at Google, one of the problems I was asked involved the same core idea: mapping a key to a value so the program can find what it needs quickly. If you want to build software that can answer questions, organize information, or retrieve the right result in a split second, you need a tool that turns a label into an index, an index into a location, and a location into a value. That tool is the Python dictionary.
Why Dictionaries Matter: The Lookup Mechanism
A Python dictionary (or dict) is a built-in data structure for storing and retrieving information by key. Unlike a list, which finds items by position (index), a dictionary finds items by label (key). This is the difference between flipping through every entry in a phone book versus jumping straight to the name you want.
A visual breakdown of how Python retrieves a value from a dictionary using a key: the key is hashed to find an index, which leads directly to the stored value. This mechanism enables fast lookups regardless of dictionary size.
<!-- worldmonger:diagram:end id="dictionary-lookup-mechanism" -->Let's see a dictionary in action right away:
## Create a dictionary mapping guest names to ages
guest_ages = {
"Alice": 29,
"Bob": 34,
"Charlie": 27
}
print(guest_ages["Alice"])
29
But why is dictionary lookup so fast? Under the hood, Python dictionaries use a data structure called a hash table. When you ask for guest_ages["Alice"], Python takes the key ("Alice"), runs it through a hash function to get a number (the index), and uses that number to jump directly to the slot where the value is stored (the location). Most of the time, this means you can retrieve, insert, or delete a value in approximately constant time—engineers call this O(1) average-case time complexity. In plain English: the time it takes to find a value doesn't grow with the size of the dictionary, at least on average. You don't have to scan every item from the beginning; you go straight from label to index to value.
Tip: This is the same engineering principle that powers web search. A search engine builds an index over documents so it can answer queries quickly, without reading every page from start to finish. A Python hash table and a search engine's inverted index are different structures, but both exist to make repeated lookup fast by building an index first.
Lists vs. Dictionaries: When to Use Each
If you’ve already learned about Lists in Python, you know that lists are great for storing ordered collections of items you access by position. But lists are not optimized for finding a value by label. If you want to know the price of a product by its code, or the grade for a student by their ID, a dictionary is the right tool.
| Data Structure | How You Access Items | Use This When... |
|---|---|---|
| List | By index (number) | You care about order or need to process every item |
| Dictionary | By key (label or ID) | You need fast lookup by label, name, or ID |
I reach for a dictionary whenever the real question is, “What value belongs to this label?”
Anatomy of a Python Dictionary: Keys and Values
A dictionary is a set of key-value pairs. Each key must be unique and immutable (strings, numbers, or tuples are common). Each value can be any Python object.
## Example: mapping guest names to ages
## (already created above as guest_ages)
print(guest_ages)
{'Alice': 29, 'Bob': 34, 'Charlie': 27}
- Keys: "Alice", "Bob", "Charlie" (labels)
- Values: 29, 34, 27 (data)
You access a value by its key. When you write guest_ages["Alice"], Python hashes the label, finds the index, locates the value, and returns it.
If you try to access a key that isn’t present, Python raises a KeyError exception. This is Python’s way of signaling that the label you provided doesn’t map to any value in the dictionary. For example, running the following code will cause an error:
print(guest_ages["Dana"])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'Dana'
This error output means Python could not find the label "Dana" in the dictionary.
Adding, Updating, and Removing Items
The next examples continue from the same guest_ages dictionary above. If you are copying code snippets independently, make sure to define guest_ages as shown earlier.
Assignment in a dictionary uses the same label → index → location → value mechanism. When you assign to a key, Python hashes the label, finds the index, and either adds a new value or replaces the existing one at that location.
## Add a new guest
guest_ages["Dana"] = 31
## Update an existing guest's age
guest_ages["Alice"] = 30
## Remove a guest
del guest_ages["Bob"]
print(guest_ages)
{'Alice': 30, 'Charlie': 27, 'Dana': 31}
Checking for Keys and Safe Lookup
To check if a key exists, use the in keyword. This checks whether the label is present among the dictionary's keys—not its values:
if "Charlie" in guest_ages:
print("Charlie is on the list!")
Charlie is on the list!
Tip:
"Charlie" in guest_ageschecks for the label as a key. If you want to check for a value, usein guest_ages.values()instead.
To avoid errors when a key might be missing, use .get(). This method follows the same lookup path—label to index to value—but instead of raising an error, it returns a fallback value if the label isn’t found:
print(guest_ages.get("Eve", "Not found"))
Not found
.get() is your safety net for uncertain lookups.
Looping Through a Dictionary
Direct lookup uses a key to jump straight to a value. But sometimes you want to process every item in the dictionary. When you loop through a dictionary, you are iterating over its keys (labels), values, or both. This is sequential traversal, not direct lookup:
## Loop over keys
for name in guest_ages:
print(name)
## Loop over values
for age in guest_ages.values():
print(age)
## Loop over key-value pairs
for name, age in guest_ages.items():
print(f"{name} is {age} years old.")
Alice
Charlie
Dana
30
27
31
Alice is 30 years old.
Charlie is 27 years old.
Dana is 31 years old.
Essential Dictionary Methods: A Practical Recap
Here are the most useful dictionary operations for beginners, all of which you’ve seen in action above:
- Inspect contents:
len(guest_ages): Count how many key-value pairs are present.guest_ages.keys(): Get all the keys (labels).guest_ages.values(): Get all the values.guest_ages.items(): Get all key-value pairs as tuples.
- Retrieve safely:
guest_ages.get(key, default): Retrieve a value by key, or return a fallback if the label isn’t found.
- Remove and keep the value:
guest_ages.pop(key, default): Remove a key and return its value, or return a fallback if the label isn’t found.
For example, to count the number of guests:
print(len(guest_ages))
3
Or to remove and retrieve a value safely:
removed_age = guest_ages.pop("Dana", None)
print(removed_age)
print(guest_ages)
31
{'Alice': 30, 'Charlie': 27}
These methods let you inspect, retrieve, and manipulate dictionary contents with confidence.
Common Mistakes and How to Avoid Them
Common mistake: Using a list when you need to look up by label. Lists are for ordered collections; dictionaries are for labeled access.
Common mistake: Using a mutable type (like a list or another dictionary) as a key. Only immutable types (strings, numbers, tuples) can be keys.
Common mistake: Forgetting that keys must be unique. Assigning a value to an existing key replaces the old value.
Common mistake: Confusing keys and values in membership checks.
inchecks keys, not values—if you need to check for a value, usein dictionary.values().
Note: Dictionaries in Python 3.7 and later preserve the order items were added, but their main purpose is still fast lookup by key, not position-based access.
Real-World Uses: Dictionaries as Indexes
Dictionaries are not just a beginner’s tool—they’re a core building block in real software systems. For example, if you want to count how many times each word appears in a sentence, a dictionary gives you a fast way to map each word (label) to its count (value):
## Count word occurrences in a sentence
sentence = "the quick brown fox jumps over the lazy dog"
word_counts = {}
for word in sentence.split():
word_counts[word] = word_counts.get(word, 0) + 1
print(word_counts)
{'the': 2, 'quick': 1, 'brown': 1, 'fox': 1, 'jumps': 1, 'over': 1, 'lazy': 1, 'dog': 1}
This same label → index → location → value pattern powers databases, caches, compilers, and search engines: build an index, and repeated lookup becomes fast and scalable.
When to Use a Dictionary (and What to Try Next)
Use a dictionary when you need to repeatedly retrieve or update a value by a stable key, label, or ID. If you find yourself writing code that asks, “What value belongs to this label?”—reach for a dictionary.
Ready to practice? Try the Practice Exercises: Data Structures or explore related structures in Tuples and Sets in Python. Or build a dictionary mapping your favorite books to their authors, or write a function that counts how many times each word appears in a sentence.
Dictionaries are a small, accessible example of a big idea in software: build an index, and you unlock speed, organization, and power. Once you see the pattern, you’ll find it everywhere.
Want a more structured Python path?
Use the Python Starter Pack to turn scattered tutorials into a focused practice path.
Python Starter Pack
A compact LearnPyFast PDF pack covering what Python is, installation, your first program, running Python code, and Python versions.
- 5 curated chapters
- Enhanced PDF edition with bundle-only learning guidance
- Offline-friendly format for focused review
- Source article links for future online updates
Coming soon