Understanding Python Dictionaries
A Python dictionary is a versatile and powerful data structure that stores data in key-value pairs. Each unique key maps to a corresponding value. This structure is optimized for fast lookups, additions, and deletions based on the key.
Key Characteristics:
- Unique Keys: Every key within a dictionary must be unique. Attempting to assign a value to an existing key will overwrite the previous value.
- Immutable Keys: Keys must be of an immutable data type, such as strings, numbers, or tuples. Mutable types like lists cannot be used as keys.
- Mutable Values: Values can be of any data type, including mutable types like lists or other dictionaries, and they do not need to be unique.
- Mutable Collection: The dictionary itself is a mutable object, meaning you can change its content—add, remove, or modify key-value pairs—after it has been created.
- Ordering: While historically considered unordered, dictionaries in Python 3.7 and later preserve the insertion order of items.
Creating Dictionaries
Dictionaries can be instantiated in several ways, most common using curly braces {}.
# Creating a dictionary with multiple key-value pairs
student_grades = {
"Alice": 92,
"Bob": 85,
"Charlie": 98
}
print(student_grades)
print(type(student_grades)) # Output: <class 'dict'>
# Creating an empty dictionary
empty_config = {}
print(empty_config)
# Creating a dictionary with a single item
single_item = {"status": "active"}
print(single_item)
Accessing Dictionary Elements
You can retrieve the value associated with a key using two primary methods, each with distinct behavior when a key is not found.
1. Using Square Bracket Notation \[\]
This method raises a KeyError if the specified key does not exist in the dictionary.
product_prices = {"apple": 1.20, "banana": 0.50, "cherry": 2.50}
# Accessing an existing key
print(product_prices["apple"]) # Output: 1.2
# Accessing a non-existent key will raise an error
# print(product_prices["orange"]) # Raises KeyError
2. Using the .get() Method
This method returns None by default if the key is not found, avoiding a program crash. You can also provide a custom default value to be returned instead of None.
inventory = {"laptop": 10, "mouse": 25, "keyboard": 15}
# Accessing an existing key
print(inventory.get("mouse")) # Output: 25
# Accessing a non-existent key returns None
print(inventory.get("monitor")) # Output: None
# Accessing a non-existent key with a default value
print(inventory.get("webcam", 0)) # Output: 0
Checking for Key Existence
To determine if a key is present in a dictionary without causing an error, use the in or not in membership operators directly on the dictionary object.
server_config = {"host": "127.0.0.1", "port": 8080, "mode": "debug"}
# Check for a key that exists
print("host" in server_config) # Output: True
print("host" not in server_config) # Output: False
# Check for a key that does not exist
print("ssl" in server_config) # Output: False
print("ssl" not in server_config) # Output: True
Modifying Dictionaries
As mutable objects, dictionaries can be easily modified through addition, deletion, and updating of their elements.
user_profile = {"username": "dev_user", "role": "editor", "active": True}
print(f"Initial: {user_profile}")
# Add a new element
user_profile["last_login"] = "2023-10-27"
print(f"After adding: {user_profile}")
# Delete an element using its key
removed_role = user_profile.pop("role")
print(f"After deleting 'role': {user_profile}")
print(f"Removed value: {removed_role}")
# Update the value of an existing key
user_profile["active"] = False
print(f"After updating: {user_profile}")
# Check the dictionary's length
print(f"Number of items: {len(user_profile)}")
Iterating Over Dictionaries
Python offers convenient ways to loop through the keys, values, or key-value pairs of a dictionary.
1. Iterating Over Keys (Default)
A simple for loop on a dictionary iterates over its keys by default.
fruit_colors = {"apple": "red", "banana": "yellow", "grape": "purple"}
for fruit in fruit_colors:
print(f"{fruit} is {fruit_colors[fruit]}")
2. Iterating Over Keys Explicitly with .keys()
The .keys() method returns a view object containing all the dictionary's keys.
for key in fruit_colors.keys():
print(f"Key: {key}")
3. Iterating Over Values with .values()
The .values() method returns a view object containing all the dictionary's values.
for color in fruit_colors.values():
print(f"Color: {color}")
4. Iterating Over Key-Value Pairs with .items()
The .items() method returns a view object that yields key-value tuples, which is ideal for unpacking in a loop.
for fruit, color in fruit_colors.items():
print(f"The color of {fruit} is {color}.")
5. Practical Example: Processing a List of Dictionaries
Dictionaries are often used to structure records, such as in JSON-like data.
log_entries = [
{"event": "login", "user_id": 101, "timestamp": "2023-10-27T10:00:00Z"},
{"event": "purchase", "user_id": 102, "timestamp": "2023-10-27T10:05:00Z"},
{"event": "logout", "user_id": 101, "timestamp": "2023-10-27T10:10:00Z"}
]
for entry in log_entries:
event_type = entry.get("event")
user = entry.get("user_id")
print(f"User {user} performed a '{event_type}' action.")