Dictionaries and Dictionary Operations
Dictionaries in Python are versatile data structures that allow you to store collections of key-value pairs. Each key is unique and maps to a specific value, similar to a real-world dictionary where words (keys) are associated with definitions (values). This section covers the basics of dictionaries and common dictionary operations.
1. Creating Dictionaries
You can create a dictionary using curly braces {}
and specifying key-value pairs separated by colons :
.
student = {"name": "Alice", "age": 25, "major": "Computer Science"}
2. Accessing Dictionary Elements
You can access the values associated with keys in a dictionary by using square brackets []
and specifying the key.
name = student["name"]
age = student["age"]
3. Modifying and Adding Elements
Dictionaries are mutable, so you can change the value associated with a key or add new key-value pairs.
student["age"] = 26 # Modify the age
student["GPA"] = 3.7 # Add a GPA key-value pair
4. Removing Elements
You can remove key-value pairs using the del
statement, specifying the key to delete.
del student["GPA"] # Remove the GPA key-value pair
5. Dictionary Operations
Dictionaries support various operations, such as checking for key existence, getting the number of key-value pairs, and listing keys and values.
student = {"name": "Alice", "age": 25, "major": "Computer Science"}
has_major = "major" in student # Check if "major" key exists
num_attributes = len(student) # Get the number of key-value pairs
keys = student.keys() # Get a list of keys
values = student.values() # Get a list of values
6. Iterating Over Dictionaries
You can loop through the keys or key-value pairs in a dictionary using a for
loop.
student = {"name": "Alice", "age": 25, "major": "Computer Science"}
# Iterate over keys
for key in student:
print(key) # Prints "name", "age", "major"
# Iterate over key-value pairs
for key, value in student.items():
print(key, value)
7. Dictionary Comprehensions
You can create dictionaries using dictionary comprehensions, which are concise expressions for creating dictionaries.
squared_numbers = {x: x ** 2 for x in range(1, 6)}
This creates a dictionary that maps numbers from 1 to 5 to their squares.
Dictionaries are widely used in Python for various applications, including storing configuration settings, data retrieval, and mapping relationships between items. Understanding how to create, access, and manipulate dictionaries is essential for working with structured data.