Home > Enterprise >  creating a dictionary out of a file, and then somehow adding a 2nd value to one of the keys
creating a dictionary out of a file, and then somehow adding a 2nd value to one of the keys

Time:11-08

Say I got a file that is

1 hchen 50
2 vryzhikov 60
3 kmannock 74
4 vryzhikov 53

I make a dictionary of the names as keys and the scores as the values. If someone has 2 different scores, both scores would come out with that name.

Something like this:

hchen 50
vryzhikov 53 60
kmannock 74
infile= open("students.txt", "r")
d = {}
with open("students.txt") as f:
    for line in f:
        a = line.split()
        key = a[1]
        val = a[2]
        d[(key)] = val



print(d)

A = input()
print(d.get(A))

is it possible to get what I'm going for?

CodePudding user response:

To open a file and read it to the dictionary you can use:

out = {}
with open("students.txt", "r") as f_in:
    for line in map(str.strip, f_in):
        if line == "":
            continue
        _, key, val = line.split()
        out.setdefault(key, []).append(val)

print(out)

Prints:

{"hchen": ["50"], "vryzhikov": ["60", "53"], "kmannock": ["74"]}

For formatted print use then:

for k, v in out.items():
    print(k, *v)

Prints:

hchen 50
vryzhikov 60 53
kmannock 74

CodePudding user response:

You could use a defaultdict where the value type is a list:

from collections import defaultdict
    
infile= open("students.txt", "r")
d = defaultdict(lambda: [])

with open("students.txt") as f:
    for line in f:
        a = line.split()
        key = a[1]
        val = a[2]
        d[key].append(val)

print(dict(d))

Which would output:

{'hchen': ['50'], 'vryzhikov': ['60', '53'], 'kmannock': ['74']}
  • Related