How to create complicated dict of lists? Pomocy:(

0

I have three files: Let's assume they look like this.
Of course solution is invalid, but maybe you have some other solutions.. I'm not asking you to write entire code, just give me tips on how to solve the problem. Thanks :)

(Alex 12 13 15
Matt 11 34.7
Grad 4.5)

(Alex 45 45.5
Grad 12 68.6
Flin 2.3)

(Grad 11.1
Mike 1.1
Flin 1.1 56.6)

As you see, some of names are repeated, some are not. I'd like to build dictionary, which would probably look like:

{'Alex' : [12,45], 'Matt' : [11] etc.}

and after that calculate average of numbers in list for every key.

If I had code, I wouldn't ask for help, but... I tried:

#!/usr/bin/env python3

import sys
import copy

file1 = sys.argv[1]
file2 = sys.argv[2]
#file3 = sys.argv[3]

name_dict = {}

firstfile = open(file1, 'r')
for line in firstfile:
line = line.rstrip().split('\t')
#print(line)
if len(line) > 1:
numberlist = line[1:]
name_dict[line[0]] = numberlist
#print(name_dict)
firstfile.close()

secondfile = open(file2, 'r')
for line in secondfile:
line = line.rstrip().split('\t')
if line[0] in name_dict.keys(): #If name is already in a dict
name_dict[line[0]].append(line[1:]) # Add number to list of nrs
else:
name_dict[line[0]] = line[1:] #If name's not in a dict yet
# add key:value pair
secondfile.close()

suma = 0 #calculate average for every key:value pair for v in name_dict.values():
length = len(v)
for element in range((length)):
suma = suma + element
average = suma/length
print(average)

#repeat for file3

Of course solution is invalid, but maybe you have some other solutions.. I'm not asking you to write entire code, just give me tips on how to solve the problem. Thanks :)

1

{'Alex' : [12,45], 'Matt' : [11] etc.}

> cat * | python3 -c 'import collections, sys; d = collections.defaultdict(list); {d[name].append(float(first)) for ln in sys.stdin for name, first, *rest in (ln.split(),)}; print(d)'
defaultdict(<class 'list'>, {'Alex': [12.0, 45.0], 'Matt': [11.0], 'Grad': [4.5, 12.0, 11.1], 'Flin': [2.3, 1.1], 'Mike': [1.1]})
> 

numberlist = line[1:]
name_dict[line[0]] = numberlist

> cat * | python3 -c 'import collections, sys; d = collections.defaultdict(list); {d[name].extend(map(float, numbers)) for ln in sys.stdin for name, *numbers in (ln.split(),)}; print(d)'
defaultdict(<class 'list'>, {'Alex': [12.0, 13.0, 15.0, 45.0, 45.5], 'Matt': [11.0, 34.7], 'Grad': [4.5, 12.0, 68.6, 11.1], 'Flin': [2.3, 1.1, 56.6], 'Mike': [1.1]})
> 

1 użytkowników online, w tym zalogowanych: 0, gości: 1