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: #
1# Empty dictionary
2my_dict = {}
3
4# Dictionary with key-value pairs
5person = {
6 "name": "Alice",
7 "age": 30,
8 "city": "New York"
9}
You can access dictionary values by referring to their keys:
1print(person["name"]) # Outputs: Alice
2print(person["age"]) # Outputs: 30
Adding, Updating, and Removing Dictionary Entries #
You can add new key-value pairs or update existing ones in a dictionary:
1# Adding a new entry
2person["job"] = "Engineer"
3
4# Updating an existing entry
5person["age"] = 31
6
7# Removing an entry
8del person["city"]
9
10print(person) # Outputs: {'name': 'Alice', 'age': 31, 'job': 'Engineer'}
Dictionary Methods #
Python provides several built-in methods to work with dictionaries:
1# Get all keys
2print(person.keys()) # Outputs: dict_keys(['name', 'age', 'job'])
3
4# Get all values
5print(person.values()) # Outputs: dict_values(['Alice', 31, 'Engineer'])
6
7# Get key-value pairs
8print(person.items()) # Outputs: dict_items([('name', 'Alice'), ('age', 31), ('job', 'Engineer')])
9
10# Check if a key exists
11if "name" in person:
12 print("Name is present in the dictionary.")
Nested Dictionaries #
Dictionaries can also contain other dictionaries, allowing you to store more complex data structures.
1people = {
2 "person1": {
3 "name": "Alice",
4 "age": 30
5 },
6 "person2": {
7 "name": "Bob",
8 "age": 25
9 }
10}
11
12print(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: #
1# Empty set
2my_set = set()
3
4# Set with unique elements
5fruits = {"apple", "banana", "cherry", "apple"}
6print(fruits) # Outputs: {'apple', 'banana', 'cherry'}
Set Operations #
Python sets support various operations for handling unique elements:
1# Adding elements
2fruits.add("orange")
3
4# Removing elements
5fruits.remove("banana")
6
7# Set operations
8set1 = {1, 2, 3}
9set2 = {3, 4, 5}
10
11# Union (all unique elements from both sets)
12print(set1 | set2) # Outputs: {1, 2, 3, 4, 5}
13
14# Intersection (common elements in both sets)
15print(set1 & set2) # Outputs: {3}
16
17# Difference (elements in set1 but not in set2)
18print(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:
1phone_book = {}
2
3def add_contact(name, phone):
4 if name in phone_book:
5 print(f"{name} is already in the phone book.")
6 else:
7 phone_book[name] = phone
8 print(f"Added {name}: {phone}")
9
10def search_contact(name):
11 if name in phone_book:
12 print(f"{name}: {phone_book[name]}")
13 else:
14 print(f"{name} is not found in the phone book.")
15
16def remove_contact(name):
17 if name in phone_book:
18 del phone_book[name]
19 print(f"Removed {name}")
20 else:
21 print(f"{name} is not found in the phone book.")
22
23# Example usage
24add_contact("Alice", "123-456-7890")
25add_contact("Bob", "987-654-3210")
26search_contact("Alice")
27remove_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!