Learn Python: Dictionaries (Key-Value Pairs)
A dictionary in Python is a collection of key-value pairs, allowing you to store data that’s more descriptive and efficient for lookups. Instead of accessing items by index, you access them by key, which can be any immutable type (commonly strings or numbers). Dictionaries are created using curly braces with key-value pairs or by calling dict(). This lesson explains how to create, update, retrieve, and iterate over dictionaries in Python using Visual Studio Code (VS Code) as your development environment.
What will be covered
• Creating dictionaries with curly braces or using dict().
• Adding, updating, and removing entries.
• Retrieving values by key, handling missing keys with in or .get().
• Looping over keys, values, or key-value pairs.
• Common dictionary methods such as .keys(), .values(), and .items().
Creating a Dictionary
You can create a dictionary by enclosing key-value pairs in curly braces. Each key is followed by a colon, and each pair is separated by commas. For example:
phone_book = {
"Alice": "123-4567",
"Bob": "987-6543",
"Carol": "555-0000"
}
print(phone_book)
This creates a dictionary mapping names to phone numbers. You could also do dict(Alice="123-4567", Bob="987-6543") to achieve a similar result.
Accessing and Updating Values
Access a value by referencing its key inside square brackets. If the key isn’t in the dictionary, Python raises a KeyError. You can also use .get() to provide a default if the key is missing. Adding or updating is as simple as assigning a value to a key.
print(phone_book["Alice"])
print(phone_book.get("Dave", "Not found"))
phone_book["Dave"] = "777-1111"
print(phone_book["Dave"])
If “Dave” was not already in phone_book, it’s automatically added with the new number. If you reassign that key later, you update the existing value.
Removing Entries
Delete a key-value pair with del phone_book["Bob"] or use .pop() if you want the removed value returned. If you try to remove a non-existent key with del, Python raises an error, but .pop() can handle a default if the key isn’t found (optional second argument).
del phone_book["Carol"]
removed_number = phone_book.pop("Alice")
print("Removed:", removed_number)
print(phone_book)
After this code, Bob remains, but Carol and Alice are gone.
Looping Through Dictionaries
You can loop through the keys in a dictionary by default, or use .values() to iterate over values, or .items() for key-value pairs. The in operator checks if a particular key is present.
for name in phone_book:
print("Key:", name)
for name, number in phone_book.items():
print("Name:", name, "Number:", number)
if "Bob" in phone_book:
print("Bob is in the dictionary.")
phone_book.keys() returns all the keys, phone_book.values() all the values, and phone_book.items() pairs of (key, value). You can convert them to a list if needed, or just iterate directly.
Practice Exercises
- Create a dictionary phone_book with at least three contacts. Print the entire dictionary. Then retrieve and print the phone number of one contact using their key.
- Add a new contact to phone_book and remove one of the existing contacts by key. Print the dictionary after each change.
- Loop through the dictionary and print each contact’s name and number in a nicely formatted string like "Name: Number". Use .items() to grab the pairs.
- Use the in operator to see if a name (like "Dave") is in the dictionary keys. Print a message depending on whether it’s found or not.
- Optional: try phone_book.get("Eve", "No entry") to handle a missing key gracefully. Print the result.
Summary
Dictionaries provide a powerful way to store data by mapping keys to values. You can add or update entries simply by assigning dict[key] = value. If a key does not exist, it’s automatically created; if it does, the value is replaced. Deleting entries uses del or .pop(). Checking membership with in avoids key errors, and you can iterate over keys, values, or both using dictionary methods. Mastering dictionaries is essential for tasks like caching results, handling user settings, and working with JSON-like structures in Python.