Use case of Python Set datatype
2 min readOct 25, 2019
A Set in Python : A Set is an unordered collection data type that is iterable, mutable, and has no duplicate elements.
# Lets create a Dictionary, with its values as Setcocktail = {
'martini': {'vodka', 'vermouth'},
'black russian': {'vodka', 'kahlua'},
'white russian': {'cream', 'kahlua', 'vodka'},
'manhattan': {'rye', 'vermouth', 'bitters'},
'screwdriver':{'orange juice', 'vodka'}}# Que: Find all drinks which contain vodka
# Example of element present in a setfor (drink, contents) in cocktail.items():
if 'vodka' in contents:
print(drink)Output:
martini
black russian
white russian
screwdriver# Que: Find all drinks which have vodka , but not vermouth along with it
# Example of intersection
for drink, contents in cocktail.items():
if 'vodka' in contents and not contents & {'vermouth'}:
print(drink, " - ", contents)
Output:
black russian - {'kahlua', 'vodka'}
white russian - {'cream', 'kahlua', 'vodka'}
screwdriver - {'vodka', 'orange juice'}# Find any drink that has vermouth or orange juice
for drink,contents in cocktail.items():
if contents & {'vermouth', 'orange juice'}:
print(drink, "-", contents)
Output:-
martini - {'vermouth', 'vodka'}
manhattan - {'vermouth', 'bitters', 'rye'}
screwdriver - {'vodka', 'orange juice'}
# Find what all drinks needed if you want to serve martini and screwdriver
print(cocktail['martini'] | cocktail['screwdriver']);
Output:-
{'vermouth', 'orange juice', 'vodka'}
# If you have drinks needed for martini , find what all extra drinks are needed to make manhattan
cocktail['manhattan'] - cocktail['martini']
Output:
{'bitters', 'rye'}
# Find drinks which are not common in 'martini' and 'black russian'
print(cocktail['martini'] ^ cocktail['black russian'])
Output:
{'vermouth', 'kahlua'}
#Find all drinks which have atleast same contents as 'black russian'
for drink, contents in cocktail.items():
if contents > cocktail['black russian']:
print(drink, "-", contents)
Output:
white russian - {'cream', 'kahlua', 'vodka'}