0 votes
1 view
ago in Python by (19.5k points)

I'm trying to take a file that looks like this

AAA x 111 AAB x 111 AAA x 112 AAC x 123 ...

And use a dictionary to so that the output looks like this

{AAA: ['111', '112'], AAB: ['111'], AAC: [123], ...}

This is what I've tried

file = open("filename.txt", "r") 

readline = file.readline().rstrip() 

while readline!= "": 

   list = [] 

   list = readline.split(" ") 

   j = list.index("x") 

   k = list[0:j] 

   v = list[j + 1:] 

   d = {} 

   if k not in d == False: 

       d[k] = [] 

   d[k].append(v) 

   readline = file.readline().rstrip()

I keep getting a TypeError: unhashable type: 'list'. I know that keys in a dictionary can't be lists but I'm trying to make my value into a list not the key. I'm wondering if I made a mistake somewhere.

1 Answer

0 votes
ago by (46.1k points)

To get rid of the error you can use below-mentioned code:-

with open('filename.txt', 'rb') as f: 

d = {} 

f.readlines(): 

line = line.split('x') 

key = line[0].strip() 

value = line[1].strip() 

if key in d: 

d[key].append(value) 

else: 

d[key] = [value] 

print d

...