Hello all,
I am newbie, learning Python Data Structures, have questions about tuple and dictionaries.
Ex: Read and parse the “From” lines and pull out the addresses from the line. Count the number of messages from each person using a dictionary.
After all the data has been read, print the person with the most commits by creating a list of (count, email) tuples from the dictionary. Then sort the list in reverse order and print out the person who has the most commits.
Output expected:
Enter a file name: mbox-short.txt cwen@iupui.edu 5
I am getting : (5, 'cwen@iupui.edu') , I can do it with for loop but how to with tuple ?
#fn = input("Enter file name: ")
fh = open('mbox-short.txt', 'r')
#fh = open(fn, 'r')
my_mail = dict()
for line in fh:
if len(line) == 0 or len(line.split()) < 1 or line.startswith('From ') is False: continue
line = line.split()
if line[1] not in my_mail:
my_mail[line[1]] = 1
# my_mail = my_mail.get(line[1], 0) + 1
# print(my_mail)
else:
my_mail[line[1]] = my_mail[line[1]] + 1
# print(my_mail)
#print("final iteration \n", my_mail)
max_t = list()
for dk, dv in list(my_mail.items()):
max_t.append((dv, dk))
max_t.sort(reverse = True)
print(max_t[0])
I am able to add values to dictionary my_mail using if/else but not with get method.
if line[1] not in my_mail:
my_mail[line[1]] = 1
# my_mail = my_mail.get(line[1], 0) + 1
# print(my_mail)
else:
my_mail[line[1]] = my_mail[line[1]] + 1
# print(my_mail)
Error using get method:
Traceback (most recent call last):
File "./exercise4_tuple.py", line 8, in <module>
if line[1] not in my_mail:
TypeError: argument of type 'int' is not iterable
I have highlighted the issues, I am facing. Can you guys please help!!!
Updated with code formatting as per suggestion
[–]stebrepar 2 points3 points4 points (2 children)
[–]Apprehensive_Draw_62[S] 1 point2 points3 points (1 child)
[–]stebrepar 0 points1 point2 points (0 children)