Professional Documents
Culture Documents
# Set Operations in Python
# Set Operations in Python
In [108…
# Set Operations in Python
first = {1, 2, 3, 4, 5, 6}
second = {4, 5, 6, 7, 8, 9}
Union: {1, 2, 3, 4, 5, 6, 7, 8, 9}
Intersection: {4, 5, 6}
Difference: {1, 2, 3}
Difference: {8, 9, 7}
Symmetric difference : {1, 2, 3, 7, 8, 9}
Symmetric difference : {1, 2, 3, 7, 8, 9}
In [109…
# Dictionaries
dict = {'math': 45, 'english': 60, 'science': 65,
x = dict['science']
print(x)
dict['english'] = 80
print(dict)
del dict['math']
print(dict)
x = 'english' in dict
y = 'hindi' not in dict
print(x)
print(y)
65
{'math': 45, 'english': 80, 'science': 65, 'computer science': 70}
{'english': 80, 'science': 65, 'computer science': 70}
True
True
True
False
Q2.Perform all python built in set and Dictionary methods. Set
In [110…
fruits = {"apple", "banana", "cherry"}
fruits.add("orange")
print(fruits)
In [111…
x=fruits.copy()
print(x)
In [112…
x.clear()
print(x)
set()
In [113…
y={"google", "microsoft", "apple"}
print(fruits.difference(y))
In [114…
fruits.difference_update(y)
print(fruits)
print(fruits.intersection(y))
fruits.discard('banana')
fruits
print(fruits.pop())
print(fruits)
fruits.remove("apple")
print(fruits)
print(x.symmetric_difference(y))
In [115…
# Dictionaries
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
car.clear()
print(car)
{}
In [116…
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.copy()
print(x)
In [117…
x = ('key1', 'key2', 'key3')
y = 0
thisdict = dict.fromkeys(x, y)
print(thisdict)
In [118…
x = car.get("model")
print(x)
Mustang
In [119…
x = car.items()
print(x)
In [120…
x = car.keys()
print(x)
In [121…
car.pop("model")
print(car)
In [122…
car.popitem()
print(car)
{'brand': 'Ford'}
In [123…
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.setdefault("model", "Bronco")
print(x)
car.update({"color": "White"})
print(car)
x = car.values()
print(x)
Mustang
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'White'}
dict_values(['Ford', 'Mustang', 1964, 'White'])
Q3. Write a program to read through the mbox-short.txt and figure out who has sent the greatest number of mail messages. The program looks for 'From ' lines and takes the
second word of those lines as the person who sent the mail. The program creates a Python dictionary that maps the sender's mail address to a count of the number of times
they appear in the file. After the dictionary is produced, the program reads through the dictionary using a maximum loop to find the most prolific committer.
In [1]:
fname = input("Enter file:")
if len(fname) < 1 : name = "mbox-short.txt"
hand = open(fname)
lst = list()
counts = dict()
for word in lst:
counts[word] = counts.get(word,0) + 1
bigcount = None
bigword = None
for word,count in counts.items():
if bigcount is None or count > bigcount:
bigcount = count
bigword = word
print (bigword,bigcount)
Enter file:mbox-short.txt
cwen@iupui.edu 5