0% found this document useful (0 votes)
3 views

Python_5

This document provides an overview of dictionaries and sets in Python, including their definitions, key operations, and examples of usage. It covers how to create, modify, and manipulate dictionaries and sets, along with hands-on exercises for practice. Additionally, it suggests resources for further learning on these data structures.

Uploaded by

infinitein093
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Python_5

This document provides an overview of dictionaries and sets in Python, including their definitions, key operations, and examples of usage. It covers how to create, modify, and manipulate dictionaries and sets, along with hands-on exercises for practice. Additionally, it suggests resources for further learning on these data structures.

Uploaded by

infinitein093
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

Day 5: Data Structures II – Dictionaries & Sets

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.

Step 1: Exploring Dictionaries

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:

# Example dictionary representing a person

person = {

"name": "Alice",

"age": 30,

"city": "New York"

print("Person dictionary:", person)

Key Operations on Dictionaries

1. Accessing Values:
Use the key inside square brackets or the .get() method.

# Using square brackets

print("Name:", person["name"])

# Using .get() method (returns None if the key is not found)

print("Age:", person.get("age"))

2. Modifying and Adding Items:


Assign a new value to an existing key or add a new key-value pair.

# Modify existing value

person["age"] = 31

print("Updated age:", person["age"])

# Add a new key-value pair


person["job"] = "Engineer"

print("After adding job:", person)

3. Removing Items:
Remove a key-value pair using the del statement or .pop() method.

# Using del to remove a key

del person["city"]

print("After removing 'city':", person)

# Using pop to remove a key and return its value

job = person.pop("job")

print("Popped job:", job)

print("Dictionary after pop:", person)

4. Looping Through a Dictionary:


Iterate over keys, values, or both.

# Loop over keys

for key in person:

print(key, "->", person[key])

# Loop over keys and values

for key, value in person.items():

print(f"{key}: {value}")

Step 2: Exploring Sets

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:

# Example set of fruits

fruits = {"apple", "banana", "cherry"}

print("Fruits set:", fruits)

Key Operations on Sets


1. Adding Elements:

fruits.add("orange")

print("After adding orange:", fruits)

2. Removing Elements:

# Using remove (raises an error if the item is not found)

fruits.remove("banana")

print("After removing banana:", fruits)

# Using discard (does nothing if the item is not found)

fruits.discard("kiwi")

print("After attempting to discard kiwi:", fruits)

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}

union = set_a | set_b # or set_a.union(set_b)

intersection = set_a & set_b # or set_a.intersection(set_b)

difference = set_a - set_b # or set_a.difference(set_b)

sym_difference = set_a ^ set_b # or set_a.symmetric_difference(set_b)

print("Union:", union)

print("Intersection:", intersection)

print("Difference (set_a - set_b):", difference)

print("Symmetric Difference:", sym_difference)

Step 3: Hands-On Exercises

Exercise 1: Dictionary Practice

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.

2. Print the capital of a specific country (e.g., "France").

3. Add a new country and its capital.

4. Remove a country from the dictionary.

5. Iterate over the dictionary and print each country and its capital.

Sample Code:

# Exercise: Country Capitals Dictionary

capitals = {

"France": "Paris",

"Germany": "Berlin",

"Italy": "Rome"

print("Capital of France:", capitals["France"])

# Add a new country-capital pair

capitals["Spain"] = "Madrid"

print("After adding Spain:", capitals)

# Remove a country (e.g., Germany)

capitals.pop("Germany")

print("After removing Germany:", capitals)

# Loop through the dictionary

for country, capital in capitals.items():

print(f"{country}: {capital}")

Exercise 2: Set Practice

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.

3. Remove a number from the set.

4. Create another set and perform union and intersection operations.

Sample Code:

# Exercise: Unique Numbers Set

numbers = {1, 2, 2, 3, 4, 4, 5}

print("Initial numbers set (duplicates removed):", numbers)

# Add a new number

numbers.add(6)

print("After adding 6:", numbers)

# Remove a number

numbers.discard(3)

print("After discarding 3:", numbers)

# Create another set for operations

more_numbers = {4, 5, 6, 7, 8}

print("More numbers set:", more_numbers)

# Perform union and intersection

union_set = numbers | more_numbers

intersection_set = numbers & more_numbers

print("Union of both sets:", union_set)

print("Intersection of both sets:", intersection_set)

Step 4: Experiment in the Python Interactive Shell

1. Open the Python Interactive Shell:


In your terminal, type:

python
2. Try Out Dictionary and Set Commands:

# Dictionary experimentation

fruit_colors = {"apple": "red", "banana": "yellow", "grape": "purple"}

print("Fruit colors:", fruit_colors)

print("Color of apple:", fruit_colors.get("apple"))

# Set experimentation

vowels = {"a", "e", "i", "o", "u"}

print("Vowels set:", vowels)

vowels.add("y")

print("After adding 'y':", vowels)

vowels.discard("o")

print("After discarding 'o':", vowels)

3. Exit the Shell:


Type:

exit()

Step 5: Additional Learning Resources

• W3Schools – Python Dictionaries:


W3Schools Python Dictionaries

• W3Schools – Python Sets:


W3Schools Python Sets

You might also like