Operation: Sets and Dictionary
Lesson 2.3
CHAPTER
2
What are the string functions?
How do you get input
from the user?
Set Operations
In This Lesson
Operations in Dictionary
Set Operations
Set Operations
• Union
• Intersection
• Difference
• Symmetric difference
Union
• Union sets is a set of all elements from both sets.
• It is performed using the “|” operator and the
union() method.
Example
x = {1,2,3,4,5}
y = {3,4,5,6,7}
print(x|y)
print(x.union(y))
{1, 2, 3, 4, 5, 6, 7}
{1, 2, 3, 4, 5, 6, 7}
Answer This
What is a union set?
Intersection
• Intersection is sets is a set of elements that are
common to both sets.
• It uses the “&” operator and the intersection() method.
Example
x = {1,2,3,4,5}
y = {3,4,5,6,7}
print(x&y)
print(x.intersection(y))
{3, 4, 5}
{3, 4, 5}
Difference
• Difference in sets is a set where the difference of set x
to y (x - y) is a set of elements that are only in x but not
in y.
• It is performed using the “-” operator and the
difference() method.
Example
x = {1,2,3,4,5}
y = {3,4,5,6,7}
print(x-y)
print(x.difference(y))
print(y-x)
print(y.difference(x))
{1, 2}
{1, 2}
{6, 7}
{6, 7}
Symmetric Difference
• Symmetric difference in sets is a set where the
symmetric difference of x and y is a set of elements
that is not found in both sets.
• It is performed using the “^” operator and the
symmetric_difference() method.
Example
x = {1,2,3,4,5}
y = {3,4,5,6,7}
print(x^y)
print(x.symmetric_difference(y))
print(y^x)
print(y.symmetric_difference(x))
{1, 2, 6, 7}
{1, 2, 6, 7}
{1, 2, 6, 7}
{1, 2, 6, 7}
Answer This
How do you describe the symmetric
difference in sets?
Find the Union, Intersection, Difference and Symmetric
Difference of the following sets:
A = {2,4,12,42,9,17}
B = {3,12,17,5,34,7,10}
C = {34,25,7,42,4,6,11,55}
Exercise
Operations in Dictionary
Dictionary Methods
• Get()
• Clear()
• Copy()
• Items()
• Update()
• Pop()
• Zip()
Example
students = {"Name":"David","Age":16}
print(students.get("Name"))
students["Age"]=30
print(students.get("Age"))
print(students.pop("Name"))
David
30
David
Answer This
How do you differentiate set operations
from dictionary operations?
Other Dictionary Methods
• fromkeys(seq[, v])
• items()
• keys()
• popitem()
• setdefault(key[,d])
• values()
Answer This
What are the methods in accessing
the elements of the dictionary?
Create a program to convert the following lists to a
dictionary. Hint: use zip().
employee = ["Cynthia","Austin","Cesar"]
salary = [40000,30000,45000]
Output:
{'Cynthia': 40000, 'Austin': 30000, 'Cesar': 45000}
Exercise
Answer This
What are the characteristics of each
type of set operation?
Do the activity on
page 84.
Lesson Exercises

Pyhton dictionary.pdf