Python Dictionaries: Organizing Key-Value Data
Dictionaries in Python are powerful data structures that allow you to store and retrieve data using key-value pairs. They’re like real-world dictionaries, mapping a word (the key) to its definition (the value). This tutorial will guide you through creating, accessing, and manipulating dictionaries in Python.
What are Dictionaries?
A dictionary is a mutable (changeable) data structure that holds data in key-value pairs. Keys must be unique and immutable (like strings, numbers, or tuples), while values can be of any data type.
Example 1: Creating and Accessing a Simple Dictionary
Let’s create a dictionary to store the names and ages of a few friends.
# Create a dictionary
friends = {
"Alice": 30,
"Bob": 25,
"Charlie": 35
}
# Accessing values using keys
alice_age = friends["Alice"]
print(alice_age)
# Accessing values using keys
bob_age = friends["Bob"]
print(bob_age)
# Accessing values using keys
charlie_age = friends["Charlie"]
print(charlie_age)
# Demonstrating error handling - trying to access a non-existent key
# This will raise a KeyError
# try:
# david_age = friends["David"]
# except KeyError as e:
# print(f"Error: Key '{e}' not found in the dictionary.")
In this example, we first create a dictionary named `friends` with three key-value pairs. The keys are the names of our friends (strings), and the values are their ages (integers). We then access the values using their corresponding keys. A `KeyError` is raised when a key that isn't present in the dictionary is attempted to be accessed. Using a `try...except` block to handle the error gracefully is a common best practice.
# Create a dictionary
friends = {
"Alice": 30,
"Bob": 25,
"Charlie": 35
}
# Accessing values using keys
alice_age = friends["Alice"]
print(alice_age)
# Accessing values using keys
bob_age = friends["Bob"]
print(bob_age)
# Accessing values using keys
charlie_age = friends["Charlie"]
print(charlie_age)
Output:
30
25
35
Example 2: Adding and Modifying Dictionary Elements
Now, let's add a new friend to the dictionary and modify an existing age.
# Create a dictionary
friends = {
"Alice": 30,
"Bob": 25,
"Charlie": 35
}
# Adding a new element
friends["David"] = 28
# Modifying an existing element
friends["Alice"] = 31
# Printing the updated dictionary
print(friends)
Here, we add a new key-value pair ("David": 28) to the `friends` dictionary. We then modify the age of "Alice" to 31. Dictionaries are mutable, so these changes are reflected immediately.
# Create a dictionary
friends = {
"Alice": 30,
"Bob": 25,
"Charlie": 35
}
# Adding a new element
friends["David"] = 28
# Modifying an existing element
friends["Alice"] = 31
# Printing the updated dictionary
print(friends)
Output:
{'Alice': 31, 'Bob': 25, 'Charlie': 35, 'David': 28}
Example 3: Iterating Through a Dictionary
Let's iterate through the dictionary to print the names and ages of all our friends.
# Create a dictionary
friends = {
"Alice": 30,
"Bob": 25,
"Charlie": 35
}
# Iterating through the dictionary using a for loop
for name, age in friends.items():
print(f"{name} is {age} years old.")
The `friends.items()` method returns a view object containing key-value pairs from the dictionary. We use a `for` loop to unpack each pair into the `name` and `age` variables. This is a concise and Pythonic way to iterate through dictionaries.
# Create a dictionary
friends = {
"Alice": 30,
"Bob": 25,
"Charlie": 35
}
# Iterating through the dictionary using a for loop
for name, age in friends.items():
print(f"{name} is {age} years old.")
Output:
Alice is 30 years old.
Bob is 25 years old.
Charlie is 35 years old.
Key Concepts Recap
Here's a quick recap of the key concepts covered in this tutorial:
- Dictionaries store data in key-value pairs.
- Keys must be unique and immutable.
- Values can be of any data type.
- You can access values using their keys.
- You can add or modify elements using the assignment operator.
- You can iterate through dictionaries using `for` loops and the `.items()` method.



Leave a Reply