
Python dictionaries store your data in neat pairs so you can find anything in a split second. Imagine putting labels on sticky notes and slapping them on storage boxes. That is how a dictionary works in Python, and it keeps your code from turning into a mess.
Instead of using plain numbers to find items in a list, you use words or labels called keys. Each key connects directly to one piece of data, which we call a value. This simple idea makes reading, updating, and matching your code easy for anyone on your team.
What is a Python dictionary?
A Python dictionary is a collection of items stored as key and value pairs. Think of a real dictionary sitting on a desk. You look up a word to see its meaning. In Python, the word is your key and the meaning is your value.
You make a dictionary by using curly brackets with a colon between each key and value. Here is what a simple user profile looks like when you write it out in code:
Look at how clear that code is to read. If you want Sarah's age, you ask for the "age" key instead of trying to remember if her age was item number zero or item number one in a long list. You can learn more about picking data structures by checking out this guide on how to choose between lists and dictionaries in Python for your daily scripts.
Keys must be unique inside a single dictionary. You cannot have two keys with the exact same name, because Python will not know which one you want to grab. If you write the same key twice, the second value will simply write over the first one.

How do you get values out of a dictionary?
Getting data out of your dictionary takes just a few key taps. You type the name of your dictionary, add square brackets, and put the key name right inside those brackets.
print(user["name"]) # Prints: Sarah
What happens if you ask for a key that does not exist? Python throws a big error and stops your script completely. I learned this the hard way when I built my first game inventory and asked for an item the player never picked up. My program crashed instantly in front of 30 test users.
To avoid crashes, you can use the get method instead. It looks for the key safely and gives back a quiet word called None if the key is missing from your collection.
print(user.get("phone")) # Prints: None
print(user.get("phone", "No phone number")) # Prints: No phone number
The get method lets you set a backup answer, as shown in that second line. If the key is not there, Python hands back your backup text instead of stopping your code. This tiny habit keeps your app running smoothly when dealing with missing user input.
How to add, change, and remove dictionary items
Dictionaries are flexible. You can add new items or update old ones whenever your program runs. To add a brand new item, assign a value to a new key name.
scores["jordan"] = 20 # Adds a new key and value
scores["alex"] = 12 # Updates the existing score for alex
Notice how simple the syntax stays. If the key exists, Python changes its value. If the key does not exist yet, Python creates it right away on the spot.
When you need to clean up data, you have three clear choices for deleting items from your code:
- pop(): Removes a specific key and gives you back its value so you can use it somewhere else.
- del: Deletes a specific key and its value directly without returning anything.
- clear(): Wipes out every single item inside the dictionary, leaving it totally empty.
Here is a quick look at pop in action on a shopping cart dictionary:
removed_item = cart.pop("milk")
print(cart) # Prints: {"apples": 3, "bread": 2}
print(removed_item) # Prints: 1
Using pop is great when you want to log what got deleted. If you write clean code, you might also enjoy reading about Python List Comprehensions: How to Clean Up Your Code to see another fast way to process collections.
How to loop through a Python dictionary
Loops let you walk through every single item inside your dictionary one by one. You can loop through just the keys, just the values, or both at the same time.
If you use a simple for loop, Python loops through the keys by default. That is handy when you want to list every user or product name in your system.
for item in prices:
print(item)
That prints apple, banana, and orange on separate lines. But what if you need both the product name and its price? You use the items method for that task.
for item, price in prices.items():
print(f"An {item} costs ${price}")
The items method gives back two variables on every loop step. The first variable holds the key name, and the second variable holds the value connected to it. This approach saves you from typing ugly lookup code inside your loop block.
If you only care about the numbers or values, call the values method instead. For example, you can calculate the total price of all items in a store with just two lines of code:
total = sum(prices.values())
print(f"Total cost: ${total}") # Prints: Total cost: $1.5
That simple sum call extracts all numbers and adds them together instantly. Small tools like this make Python feel fast and natural to write when you work on real project builds.
Nesting dictionaries inside dictionaries
Real world data is often layered like boxes inside bigger boxes. Python lets you store dictionaries inside other dictionaries to represent complex real world information cleanly.
Imagine managing student records for a small coding class of 15 people. Every student has a unique ID number, and inside that ID, you want to store their full name, grade level, and attendance record.
"id_101": {"name": "Mia", "grade": "A", "absences": 0},
"id_102": {"name": "Liam", "grade": "B", "absences": 2}
}
To reach nested data, you chain square brackets together like a set of steps leading down to your target item.
print(students["id_102"]["absences"]) # Prints: 2
The first bracket finds student id_101, and the second bracket grabs the name from inside that specific student's record. You can nest lists inside dictionaries too, like keeping a list of favorite hobbies inside a user profile.
If you want to write neat code while processing lists inside your dictionary, check out our guide on Python List Comprehensions: How to Clean Up Your Code for extra tips. Combining nested dictionaries with fast loops turns big sets of messy data into something easy to search.
Common dictionary methods you should know
Python gives you several built-in tools to make working with dictionaries fast and predictable. Here are four essential tools you will use almost every day when building apps:
- update(): Merges another dictionary into your current one, overwriting matching keys.
- setdefault(): Returns a key's value if present, or creates the key with a default value if missing.
- keys(): Returns a handy view object containing every key stored in your dictionary.
- copy(): Creates a shallow copy of your dictionary so changes do not alter your original data.
Let us see how update works when combining two user profile settings into one master dictionary:
user_settings = {"theme": "dark"}
defaults.update(user_settings)
print(defaults) # Prints: {"theme": "dark", "notifications": True}
The update method swapped out the default light theme for the dark theme picked by the user, but left notifications set to True. This design pattern works well for web apps saving custom settings. You can dive into more scripts like this by reading our piece on how to build useful Python automation tools to handle daily tasks.
Dictionaries form the backbone of modern web data format called JSON. When you pull weather forecasts, stock prices, or social media posts from web APIs, that data arrives structured like a big Python dictionary.
Tips to start using dictionaries today
Mastering dictionaries comes down to building tiny projects and fixing errors as you learn. Here are three practical tips you can use right now to improve your Python programs:
- Always default to .get(): Stop using square brackets when reading values from dynamic sources like user input or web requests to avoid sudden KeyError crashes.
- Use descriptive key names: Stick to simple string labels like "email_address" instead of short codes like "ea" so anyone reading your code understands it instantly.
- Check keys with 'in': Use the simple expression
if "key" in my_dict:before doing complex math or edits on values.
Dictionaries make your data structured, searchable, and easy to read. Try opening your code editor today and converting a few loose variables into a neat dictionary layout. What data in your current project could use clear key labels right now?