Python_5
Python_5
Today, you'll learn how to work with dictionaries and sets—two essential data structures in Python
that help you manage data in versatile ways.
What is a Dictionary?
• Definition:
A dictionary is an unordered collection of key-value pairs. Each key is unique and is used to
store and retrieve its associated value. Dictionaries are mutable, meaning you can change
them after creation.
• Creating a Dictionary:
person = {
"name": "Alice",
"age": 30,
1. Accessing Values:
Use the key inside square brackets or the .get() method.
print("Name:", person["name"])
print("Age:", person.get("age"))
person["age"] = 31
3. Removing Items:
Remove a key-value pair using the del statement or .pop() method.
del person["city"]
job = person.pop("job")
print(f"{key}: {value}")
What is a Set?
• Definition:
A set is an unordered collection of unique elements. Sets are mutable (you can add or
remove items), but the elements contained in a set must be immutable (e.g., numbers,
strings, tuples).
• Creating a Set:
fruits.add("orange")
2. Removing Elements:
fruits.remove("banana")
fruits.discard("kiwi")
3. Set Operations:
Sets support mathematical operations such as union, intersection, difference, and
symmetric difference.
set_a = {1, 2, 3, 4}
set_b = {3, 4, 5, 6}
print("Union:", union)
print("Intersection:", intersection)
Task:
Create a dictionary that maps several countries to their capitals, and then manipulate it.
Steps:
1. Create a dictionary called capitals with at least three country-capital pairs.
5. Iterate over the dictionary and print each country and its capital.
Sample Code:
capitals = {
"France": "Paris",
"Germany": "Berlin",
"Italy": "Rome"
capitals["Spain"] = "Madrid"
capitals.pop("Germany")
print(f"{country}: {capital}")
Task:
Create a set of unique numbers, and then perform some set operations.
Steps:
1. Create a set named numbers with some duplicate values to see that duplicates are
automatically removed.
2. Add a new number to the set.
Sample Code:
numbers = {1, 2, 2, 3, 4, 4, 5}
numbers.add(6)
# Remove a number
numbers.discard(3)
more_numbers = {4, 5, 6, 7, 8}
python
2. Try Out Dictionary and Set Commands:
# Dictionary experimentation
# Set experimentation
vowels.add("y")
vowels.discard("o")
exit()