Dictionaries in Python
Have you ever needed to match a name to a phone number, or a word to its definition? This idea of connecting one thing to another is everywhere in daily…
Have you ever needed to match a name to a phone number, or a word to its definition? This idea of connecting one thing to another is everywhere in daily life—and it’s just as useful in programming!
Python dictionaries make it easy to store and work with these kinds of key-value pairs in your code. In this article, you’ll learn what Python dictionaries are, why they’re so helpful, and how to use them to organize and access information quickly.
What Is a Python Dictionary?
A Python dictionary (or dict) is a built-in data structure that stores information as pairs: a key and a value. Think of a dictionary like a real-life address book. The key is the person’s name, and the value is their phone number. You look up the name (key) to find the number (value).
Unlike lists, which use numbers (indexes) to access items, dictionaries use keys—such as words, names, or IDs—to access values. This makes dictionaries perfect for situations where you want to look up information quickly by a unique label.
Real-world analogy:
- Contact list: Name → Phone number
- Glossary: Word → Definition
- Student records: Student ID → Grades
Dictionaries are flexible and can store many different types of data, making them one of the most useful Python data structures for both beginners and experts.
Why Use Dictionaries?
You might wonder, “Why not just use a list?” Here’s why Python dictionaries are often a better choice for certain tasks:
- Fast lookup: You can find a value instantly by its key, even if your dictionary has thousands or millions of items. This is much faster than searching through a list.
- Organized data: Dictionaries help you keep related information together. For example, you can store all details about a product (like name, price, and stock) in one place.
- Mapping relationships: Whenever you need to connect one thing to another—like usernames to email addresses, product codes to descriptions, or countries to capitals—a dictionary is your go-to Python data structure.
Quiz Question 1
Question: What is the main advantage of using a Python dictionary over a list for storing data?
- A) You can access values quickly using unique keys
- B) Dictionaries use less memory than lists
- C) Dictionaries automatically sort the data
- D) Dictionaries only store numbers
How Dictionaries Store Data
At the heart of every Python dict are keys and values.
A Python dictionary stores data as key-value pairs. Each unique key (like a name) points to a value (like an age), making it easy to look up information quickly.
- Key: The unique identifier you use to look up information (like a name, word, or ID).
- Value: The data or information associated with that key (like a phone number, definition, or score).
You can think of a dictionary as a set of labeled boxes. Each label (key) points to something inside the box (value).
Common types for keys and values:
- Keys are usually strings or numbers, and they must be unique within the dictionary.
- Values can be any data type—numbers, strings, lists, or even other dictionaries!
Example:
Suppose you want to store the ages of three friends:
ages = {
"Alice": 25,
"Bob": 30,
"Charlie": 22
}
Here, "Alice", "Bob", and "Charlie" are keys, and their ages are the values.
Common Dictionary Operations
Let’s look at some basic things you can do with Python dictionaries:
-
Add new key-value pairs: Assign a value to a new key to add it to the dictionary.
-
Change values for existing keys: Assign a new value to an existing key to update it.
-
Remove items: Use the
delstatement to remove a key and its value. -
Check if a key exists: Use the
inkeyword to see if a key is in the dictionary. -
Get the number of items: Use
len(dictionary)to find out how many key-value pairs are in the dictionary. -
Retrieve values safely: Use the
.get(key)method to get a value without causing an error if the key doesn’t exist.
Example:
## Add a new key-value pair
ages["Sam"] = 27
## Update an existing value
ages["Alice"] = 26
## Remove a key-value pair
del ages["Bob"]
## Check if a key exists
if "Charlie" in ages:
print("Found Charlie!")
## Get a value safely
age_of_tom = ages.get("Tom", "Not found")
Quiz Question 2
Question: Which of these is a valid way to add a new key-value pair to a Python dictionary called ages?
- A) ages["Sam"] = 27
- B) ages.add("Sam", 27)
- C) add(ages, "Sam", 27)
- D) ages.append(["Sam", 27])
Everyday Examples of Dictionaries
Python dictionaries are everywhere once you know what to look for! Here are a few practical examples:
-
Storing contact information: Pair names with phone numbers.
-
Mapping product names to prices: Assign prices to product names.
-
Organizing quiz questions and answers: Match questions to their correct answers.
Whenever you need to pair up information—like matching questions to answers or products to prices—a Python dict is the perfect tool.
Tips for Beginners
Dictionaries are beginner-friendly, but here are a few tips to help you get started:
-
Keys vs. values: The key is what you use to look up information; the value is the information itself.
-
Choose good key names: Use clear, descriptive keys (like
"email"or"price") to make your code easy to read. -
Keys must be unique: Each key in a dictionary must be different. If you add a key that already exists, the old value will be replaced.
-
Keys must be immutable: You can use strings, numbers, or tuples as keys, but not lists or other dictionaries.
-
Values can be anything: Numbers, strings, lists, or even other dictionaries.
-
Order in dictionaries: In modern Python (3.7+), dictionaries remember the order you add items, but don’t rely on this unless you specifically need it.
-
Handling missing keys: Accessing a key that doesn’t exist will cause an error. Use the
.get()method or check withinbefore accessing.
Practice and Next Steps
The best way to learn Python dictionaries is to use them! Here are some ideas to get you started:
-
Create your own dictionary: Try making a dictionary of your favorite movies and their release years.
-
Experiment: Add, update, and remove items. Check if certain keys exist. Print out all the keys and values.
-
Take a quiz: Test your understanding with the quiz questions in this article, or try some hands-on exercises.
-
Explore more: Once you’re comfortable, look into related topics like nested dictionaries (dictionaries inside dictionaries) or combining dictionaries with lists for more complex data structures.
Summary
Python dictionaries are a powerful and practical way to store and manage data as key-value pairs. They let you organize information in a way that’s easy to understand and super fast to use. As you continue your Python journey, you’ll find that dictionaries are one of the most important Python data structures you can master.
Keep practicing, experiment with your own examples, and soon you’ll be using Python dicts with confidence. Happy coding!
Quiz Answer Key
Question 1
Correct answer: A) You can access values quickly using unique keys
Explanation: Dictionaries let you look up values instantly by their keys, which is much faster than searching through a list.
Question 2
Correct answer: A) ages["Sam"] = 27
Explanation: You add a new key-value pair by assigning a value to a new key using square brackets. The other options are not valid ways to add items to a dictionary.
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