0 votes
1 view
in Python by (47.8k 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.

2 Answers

0 votes
by (107k points)
edited by

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

To know more about this you can have a look at the following video tutorial:-

0 votes
by (140 points)

The error says that you try to use a list as dictionary key, you'll have to change your list into tuples if you want to put them as keys in your dictionary. TypeError: unhashable type: 'list' usually means that you are trying to use a list as an hash argument. The only types of values not acceptable as keys are values containing lists or dictionaries or other mutable types that are compared by value rather than by object identity, the reason being that the efficient implementation of dictionaries requires a key’s hash value to remain constant.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
2 answers
0 votes
1 answer
0 votes
1 answer
asked Aug 30, 2019 in Python by Sammy (47.8k points)
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...