Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

data1.txt === http://www.cse.msu.edu/~cse231/Online/Labs/Lab09/data1.txt data2.t

ID: 3863312 • Letter: D

Question

data1.txt === http://www.cse.msu.edu/~cse231/Online/Labs/Lab09/data1.txt

data2.txt === http://www.cse.msu.edu/~cse231/Online/Labs/Lab09/data2.txt

IN Python

B. Write a program using Dictionaries Given two files named exactly "datal.txt" and "data2.txt" (no error checking needed) of names and scores print out the combined scores in alphabetical order by name. Note that the files will be formatted the same, but some names will be in both files and some names will only be in one file. Fornames in both files the scores need to be summed. The file format will be one header line followed by lines that have a name (string) and a number (int) separated by some unknown number of spaces. Requirements (1) You must use a dictionary. (2) You must use two functions that have a dictionary as an argument, e.g. read a file, print results. For example, if data1 contains Name Score 20 Joe Mary 70 Rich 50 Jose 90 and data2.txt contains Name Score Sarah 80 Ming 20 65 Oe Rich 30

Explanation / Answer

# use python 3
import itertools
import collections

record1=dict()
record2=dict()
CombinedRecord=dict()

fname1 = input("Enter file 1 : ");
fh = open(fname1);

for line in fh:
if line.startswith('Name'):continue;
line =line.upper().rstrip();
lines=line.split(" ")
name=lines[0];
score=lines[-1];
record1[name]=int(score)

fname2 = input("Enter file 2 : ");
fh2 = open(fname2);

for line in fh2:
if line.startswith('Name'):continue;
line =line.upper().rstrip();
lines=line.split(" ")
name=lines[0];
score=lines[-1];
record2[name]=int(score)
  
new_dict = collections.defaultdict(int)
for k, v in sorted(itertools.chain(record1.items(), record2.items())):
new_dict[k] += v

print (dict(new_dict))