Dictionaries and Sets: Efficient Data Retrieval #
Welcome back to our programming tutorial series! Today, we’ll explore two powerful data structures in Python: dictionaries and sets. These structures allow you to store and retrieve data efficiently, especially when working with unique values or key-value pairs.
What Are Dictionaries? #
A dictionary is an unordered collection of key-value pairs, where each key is unique. You can use a dictionary to store related pieces of information and access them using the corresponding key.
Creating Dictionaries: #
# Empty dictionary
my_dict = {}
# Dictionary with key-value pairs
person = {
"name": "Alice",
"age": 30,
"city": "New York"
}
You can access dictionary values by referring to their keys:
print(person["name"]) # Outputs: Alice
print(person["age"]) # Outputs: 30
Adding, Updating, and Removing Dictionary Entries #
You can add new key-value pairs or update existing ones in a dictionary:
# Adding a new entry
person["job"] = "Engineer"
# Updating an existing entry
person["age"] = 31
# Removing an entry
del person["city"]
print(person) # Outputs: {'name': 'Alice', 'age': 31, 'job': 'Engineer'}
Dictionary Methods #
Python provides several built-in methods to work with dictionaries:
# Get all keys
print(person.keys()) # Outputs: dict_keys(['name', 'age', 'job'])
# Get all values
print(person.values()) # Outputs: dict_values(['Alice', 31, 'Engineer'])
# Get key-value pairs
print(person.items()) # Outputs: dict_items([('name', 'Alice'), ('age', 31), ('job', 'Engineer')])
# Check if a key exists
if "name" in person:
print("Name is present in the dictionary.")
Nested Dictionaries #
Dictionaries can also contain other dictionaries, allowing you to store more complex data structures.
people = {
"person1": {
"name": "Alice",
"age": 30
},
"person2": {
"name": "Bob",
"age": 25
}
}
print(people["person1"]["name"]) # Outputs: Alice
What Are Sets? #
A set is an unordered collection of unique elements. Sets are useful when you want to store non-duplicate items or perform mathematical set operations like union, intersection, and difference.
Creating Sets: #
# Empty set
my_set = set()
# Set with unique elements
fruits = {"apple", "banana", "cherry", "apple"}
print(fruits) # Outputs: {'apple', 'banana', 'cherry'}
Set Operations #
Python sets support various operations for handling unique elements:
# Adding elements
fruits.add("orange")
# Removing elements
fruits.remove("banana")
# Set operations
set1 = {1, 2, 3}
set2 = {3, 4, 5}
# Union (all unique elements from both sets)
print(set1 | set2) # Outputs: {1, 2, 3, 4, 5}
# Intersection (common elements in both sets)
print(set1 & set2) # Outputs: {3}
# Difference (elements in set1 but not in set2)
print(set1 - set2) # Outputs: {1, 2}
Practical Exercise: Phone Book Application #
Now that you understand dictionaries and sets, let’s create a simple phone book application using dictionaries:
- Write a program that allows the user to:
- Add a new contact (name and phone number).
- Search for a contact by name.
- Remove a contact by name.
- Use a set to keep track of unique contact names.
Here’s a starter example:
phone_book = {}
def add_contact(name, phone):
if name in phone_book:
print(f"{name} is already in the phone book.")
else:
phone_book[name] = phone
print(f"Added {name}: {phone}")
def search_contact(name):
if name in phone_book:
print(f"{name}: {phone_book[name]}")
else:
print(f"{name} is not found in the phone book.")
def remove_contact(name):
if name in phone_book:
del phone_book[name]
print(f"Removed {name}")
else:
print(f"{name} is not found in the phone book.")
# Example usage
add_contact("Alice", "123-456-7890")
add_contact("Bob", "987-654-3210")
search_contact("Alice")
remove_contact("Bob")
What’s Next? #
You’ve just learned how to work with dictionaries and sets, essential tools for managing key-value pairs and unique collections of data. In the next post, we’ll dive into practical applications of these data structures to solve real-world problems.
Related Articles #
- Lists and Arrays: Storing Collections of Data
- Modules and Importing: Reusing Code Efficiently
- Control Structures: Mastering Program Flow
Happy coding, and we’ll see you in the next lesson!