Imagine you have a list of phone numbers, but instead of accessing them by a numeric index like 0 or 1, you want to look them up by a person’s name. This is exactly what a dictionary in Python is for! Dictionaries store data in key-value pairs, making them incredibly efficient for lookups.
🔑 Understanding Key-Value Pairs
Unlike a list, which is indexed by a sequence of numbers, a dictionary is indexed by keys. These keys can be strings, numbers, or other immutable types. Each key is associated with a value. Together, they form a key-value pair. You create a dictionary using curly braces {}
, with each pair written as key: value
. For example: phonebook = {"Alice": "555-1234", "Bob": "555-5678"}
.
➕ Accessing, Adding, and Modifying Data
Accessing a value is simple: you use the key inside square brackets, much like a list index. For example, phonebook["Alice"]
would return “555-1234”. Adding a new entry or modifying an existing one uses the same syntax. If the key doesn’t exist, a new key-value pair is created. If it does exist, the value is updated.phonebook["Charlie"] = "555-9999" # Adds a new entry
phonebook["Alice"] = "555-4321" # Updates an existing entry
🔄 Looping Through a Dictionary
You can easily loop through a dictionary with a for
loop. By default, looping over a dictionary gives you its keys.for name in phonebook:
print(name, phonebook[name])
If you only want to loop through the values, you can use the .values()
method, like for number in phonebook.values():
. This flexibility makes it easy to work with all the data stored inside.
Dictionaries are one of Python’s most important data structures. They are perfect for any situation where you need to store and retrieve data based on a unique identifier, rather than a simple position.
—
Stephenson, Ben. The Python Workbook: A Brief Introduction with Exercises and Solutions. 3rd ed., Springer, 2025.
More Topics
- How to Pass Command Line Arguments to Your Python Script
- Solving the Classic FizzBuzz Problem in Python: A Step-by-Step Tutorial
- How to Solve the Pythagorean Theorem with a Python Script
- What’s the Difference Between Syntax, Runtime, and Logic Errors in Python?
- Thinking Recursively: A Beginner’s Introduction to Recursion in Python
- How to Read and Write Files in Python
- How to Handle Errors Gracefully in Python with Try and Except