Chapter: Understanding Dictionaries and Sets
in Python
Author: Yogesh Sir
Introduction
In Python, dictionaries and sets are two powerful data structures that allow you to store and manipulate
data efficiently. This chapter will cover the basics of dictionaries and sets, their methods, and provide
examples to illustrate their usage.
Section 1: Dictionaries
What is a Dictionary?
A dictionary in Python is an unordered collection of items. Each item is stored as a key-value pair.
Keys must be unique and immutable (which means you can use strings, numbers, or tuples as keys),
while values can be of any data type.
Creating a Dictionary
You can create a dictionary using curly braces {} or the dict() function.
# Using curly braces
my_dict = {
"name": "Alice",
"age": 25,
"city": "New York"
}
# Using the dict() function
my_dict2 = dict(name="Bob", age=30, city="Los Angeles")
Accessing Values
You can access the values in a dictionary using their keys.
print(my_dict["name"]) # Output: Alice
print(my_dict2["age"]) # Output: 30
Dictionary Methods
Here are some commonly used dictionary methods:
1. get(key, default): Returns the value for the specified key. If the key does not exist, it
returns the default value.
print(my_dict.get("name")) # Output: Alice
print(my_dict.get("country", "USA")) # Output: USA
2. keys(): Returns a view object that displays a list of all the keys in the dictionary.
print(my_dict.keys()) # Output: dict_keys(['name', 'age', 'city'])
3. values(): Returns a view object that displays a list of all the values in the dictionary.
print(my_dict.values()) # Output: dict_values(['Alice', 25, 'New York'])
4. items(): Returns a view object that displays a list of dictionary's key-value tuple pairs.
print(my_dict.items()) # Output: dict_items([('name', 'Alice'), ('age', 25), ('city',
'New York')])
5. update(other_dict): Updates the dictionary with the key-value pairs from another
dictionary.
my_dict.update({"age": 26, "country": "USA"})
print(my_dict) # Output: {'name': 'Alice', 'age': 26, 'city': 'New York', 'country':
'USA'}
6. pop(key, default): Removes the specified key and returns its value. If the key does not exist,
it returns the default value.
age = my_dict.pop("age", "Not Found")
print(age) # Output: 26
print(my_dict) # Output: {'name': 'Alice', 'city': 'New York', 'country': 'USA'}
7. clear(): Removes all items from the dictionary.
my_dict.clear()
print(my_dict) # Output: {}
# Creating a dictionary to store student information
students = {
"001": {"name": "John", "age": 20, "major": "Computer Science"},
"002": {"name": "Jane", "age": 22, "major": "Mathematics"},
}
# Accessing student information
print(students["001"]["name"]) # Output: John
# Updating a student's major
students["001"]["major"] = "Data Science"
print(students["001"]) # Output: {'name': 'John', 'age': 20, 'major': 'Data Science'}
Section 2: Sets
What is a Set?
A set is an unordered collection of unique items. Sets are mutable, meaning you can add or remove
items after the set has been created. However, the items in a set must be immutable.
Creating a Set
You can create a set using curly braces {} or the set() function.
python
# Using curly braces
my_set = {1, 2, 3, 4, 5}
# Using the set() function
my_set2 = set([1, 2, 3, 4, 5])
Adding and Removing Items
You can add items to a set using the add() method and remove items using the remove() or
discard() methods.
my_set.add(6)
print(my_set)
# Output: {1, 2, 3, 4, 5, 6}
# Removing an item using remove() (raises KeyError if the item is not found)
my_set.remove(3)
print(my_set) # Output: {1, 2, 4, 5, 6}
# Removing an item using discard() (does not raise an error if the item is not found)
my_set.discard(10) # No error, even though 10 is not in the set
print(my_set) # Output: {1, 2, 4, 5, 6}
Set Methods
Here are some commonly used set methods:
1. union(other_set): Returns a new set with all items from both sets.
set_a = {1, 2, 3}
set_b = {3, 4, 5}
union_set = set_a.union(set_b)
print(union_set) # Output: {1, 2, 3, 4, 5}
2. intersection(other_set): Returns a new set with items that are common to both sets.
intersection_set = set_a.intersection(set_b)
print(intersection_set) # Output: {3}
3. difference(other_set): Returns a new set with items in the first set that are not in the
second set.
difference_set = set_a.difference(set_b)
print(difference_set) # Output: {1, 2}
4. symmetric_difference(other_set): Returns a new set with items in either set, but not
in both.
symmetric_difference_set = set_a.symmetric_difference(set_b)
print(symmetric_difference_set) # Output: {1, 2, 4, 5}
5. clear(): Removes all items from the set.
my_set.clear()
print(my_set) # Output: set()
Example: Using a Set
# Creating a set of unique fruits
fruits = {"apple", "banana", "cherry", "apple"} # 'apple' will only appear once
print(fruits) # Output: {'banana', 'cherry', 'apple'}
# Adding a new fruit
fruits.add("orange")
print(fruits) # Output: {'banana', 'cherry', 'apple', 'orange'}
# Removing a fruit
fruits.remove("banana")
print(fruits) # Output: {'cherry', 'apple', 'orange'}
# Checking for membership
if "apple" in fruits:
print("Apple is in the set!") # Output: Apple is in the set!
Section 3: Comparing Dictionaries and Sets
Dictionaries and sets are essential data structures in Python that provide efficient ways to store and
manipulate data. Understanding how to use them effectively will enhance your programming skills and
allow you to write more efficient and organized code. Practice using these structures with various
methods to become more comfortable with their functionalities.
Exercises
1. Create a dictionary to store information about your favorite books (title, author, year published).
Access and print the author of one of the books.
2. Create a set of your favorite colors. Add a new color to the set and remove one color. Print the
final set.
3. Write a function that takes two sets as input and returns their intersection and union.