I got two files open and read like this
file1
Name, day1
Omi Aiz,90
Carin Jack,92
Swit Han,88
file2
Name, Day2
Omi Aiz, 20
Carin Jack,30
Swit Han,40
How to combine these into a single dictionary:
d={'OA':[90,20],'CJ':[92,30],'SH':[88,40]}
And find the average of day1 and day2
d={'OA':55,'CJ':61,'SH':64}
CodePudding user response:
this should do the first part
for the second, you just loop through and do average
def get_letters(name):
names = name.split()
return f'{names[0][0]}{names[1][0]}'
with open('file1', 'r') as f1, open('file2', 'r') as f2:
d = {}
for l1, l2 in zip(f1[1:], f2[1:]):
l1 = l1.split(',')
l2 = l2.split(',')
letters = get_letters(l1[0])
d.append({letters:[l1[1], l2[1]]})
CodePudding user response:
d={}
def read(file):
with open(file) as file:
lines = file.read().split('\n')
for line in lines:
if line.startswith('Name,'):
lines.remove(line)
return lines
def sep(name):
return ''.join((v[0] for v in name.split(' ')))
d = {}
for line in read('file1.txt'):
if line:
name,day=line.split(',')
k = sep(name)
d[k] = [int(day)]
for line in read('file2.txt'):
if line:
name,day=line.split(',')
k = sep(name)
if k in d:
d[k].append(int(day))
print(d)