Reputation: 83
I have a list which is holding names as below
d=[['Srini'], ['Rahul'], ['Mano'], ['Rahul'], ['Srini'], ['Mano], ['Srini'], ['Rahul']]
I am using the below code to convert the list to dictionary which should hold names as Keys and the count of names as value.
dic={}
for words in d:
dic[words]= dic.get(words,0)+1
print(dic)
ERROR: TypeError Traceback (most recent call last) in () 1 dic={} 2 for words in d: ----> 3 dic[words]= dic.get(words,0)+1 4 print(dic)
TypeError: unhashable type: 'list'
Upvotes: 2
Views: 67
Reputation: 4814
You could try this:
dic = {}
for i in range(len(d)):
if d[i] in dic:
dic[d[i]] += 1
else:
dic[d[i]] = 1
Upvotes: 0
Reputation: 312259
List are unhashable. You could, however, assume that each sub-list has a single element and refer to it:
dic={}
for words in d:
dic[words[0]]= dic.get(words[0], 0) + 1
print(dic)
Note, BTW, that python's Counter
already has a pretty similar functionality:
from collections import Counter
print(Counter((i[0] for i in d)))
Upvotes: 2