This chapter concludes the introduction to Python’s core data structures by covering two essential unordered collections: Dictionaries (key-value pairs) and Sets (unique items).
1. Dictionaries (dict)
A Dictionary is an unordered collection of data values, used to store data in key: value pairs. Dictionaries are mutable and highly optimized for retrieving values based on a unique key.
A. Creating and Accessing Dictionaries
- Dictionaries are defined using curly braces
{}. - Keys must be unique and immutable (usually strings, numbers, or tuples). Values can be any data type.
- Values are accessed by referencing their associated key, not an index.
user_profile = {
"name": "Alex",
"age": 28,
"city": "New York",
"is_active": True
}
# Accessing a value using its key
print(user_profile["name"]) # Output: Alex
B. Modifying Dictionaries
Since dictionaries are mutable, you can add new pairs, change existing values, and remove pairs.
| Action | Syntax | Example |
| Adding/Updating | dict[new_key] = new_value | user_profile["city"] = "Boston" |
| Removing (Key exists) | del dict[key] | del user_profile["is_active"] |
| Removing & Returning | dict.pop(key) | age = user_profile.pop("age") |
user_profile["email"] = "alex@example.com" # Adds a new key-value pair
user_profile["age"] = 29 # Updates the existing age value
C. Dictionary Methods for Views
Python provides methods to retrieve views of the keys, values, and pairs for iteration.
| Method | Description |
keys() | Returns a view object of all the keys. |
values() | Returns a view object of all the values. |
items() | Returns a view object of all the key-value pairs (as tuples). |
# Iterating over all key-value pairs
for key, value in user_profile.items():
print(f"{key}: {value}")
D. Safe Access with get()
Using bracket notation (dict[key]) raises a KeyError if the key doesn’t exist, which can crash your program. The get() method is a safer way to access values, returning None (or a specified default) if the key is missing.
# Safe access
country = user_profile.get("country", "Unknown")
# Since 'country' doesn't exist, it returns 'Unknown'
2. Sets (set)
A Set is an unordered, mutable collection of unique elements. Sets are primarily used to efficiently test for membership or eliminate duplicate entries from a list.
A. Creating Sets
- Sets are defined using curly braces
{}or theset()constructor. - Note: To create an empty set, you must use
empty_set = set(), as{}creates an empty dictionary.
my_set = {"apple", "banana", "cherry", "apple"}
print(my_set)
# Output: {'apple', 'banana', 'cherry'} (The duplicate 'apple' is removed)
B. Set Operations
Sets are highly efficient for performing mathematical set operations:
| Operation | Method | Symbol | Description |
| Union | set_a.union(set_b) | ` | ` |
| Intersection | set_a.intersection(set_b) | & | Elements common to both sets. |
| Difference | set_a.difference(set_b) | - | Elements in Set A but not in Set B. |
set_a = {1, 2, 3}
set_b = {3, 4, 5}
# Find common elements
common = set_a.intersection(set_b)
print(common) # Output: {3}
