0

I have a txt file that contain the following:

Monday, 56

Tuesday, 89

Wednesday, 57

Monday, 34

Tuesday, 31

Wednesday, 99

I need it to be converted to a dictionary:

{'Monday': [56 , 34], 'Tuesday': [89, 31], 'Wednesday': [57, 99]}

Here is the code I have so far:

d = {}
with open("test.txt") as f:
    for line in f:
        (key, val) = line.split()
        d[str(key)] = val
        print(d)

And here is the result I get from it:

{'Monday,': '56'}

{'Monday,': '56', 'Tuesday,': '89'}

{'Monday,': '56', 'Tuesday,': '89', 'Wednesday,': '57'}

{'Monday,': '34', 'Tuesday,': '89', 'Wednesday,': '57'}

{'Monday,': '34', 'Tuesday,': '31', 'Wednesday,': '57'}

{'Monday,': '34', 'Tuesday,': '31', 'Wednesday,': '99'}

Can anyone help me with this?

Thanks

JTiger
  • 31
  • 6
  • 1. when you do `d[...] = val`, you _assign_ `val` to that key in the dictionary. Think about whether that's what you really need to do (hint: it isn't). 2. `line.split()` splits on spaces. You also need the comma to be removed. Think about how you can get `split()` to do it for you. – Pranav Hosangadi Aug 24 '20 at 05:30
  • Sorry I don't understand. I am very new to all of this. – JTiger Aug 24 '20 at 05:46
  • This should help: https://stackoverflow.com/a/41165767/1174966 – jdaz Aug 24 '20 at 05:46

3 Answers3

2

When you split the line you can use comma as a separator. Then after splitting the line you can check the dictionary on whether it already contain the key:

(key, val) = line.split(',')
if key in d.keys:
    d[str(key)].append(val)
else:
    d[str(key)] = [val]
print (d)
Enrico
  • 120
  • 5
2
d = {}

with open("test.txt") as f:
  for line in f:
    (key, val) = line.split()
    if not key in d.keys():
      d[key] = []

    d[key].append(val)

print (d)

This should work.

Ryan Rudes
  • 508
  • 4
  • 11
1
d = {}
with open("test.txt") as f:
    for line in f:
        (key, val) = line.split()
        if key in d:
            d[str(key)].append(val)
        else:
            d[str(key)] = [val]
print(d)

Try to add list of value in dictionary.

Vashdev Heerani
  • 660
  • 7
  • 21