typeerror: unhashable type: 'list' ,How to count occurrence of elements in python list and save it in dictionary?

Question:

     d = {}
    x = []
    l=[1,1,1,2,3,3,5,5]
    def count(lst,r):
        z = 0
        for i in lst:
            if i==r:
                z+=1
        return z
    print(count(l,1))

    def conv_to_dict(lst):
        d={}
        d={x:count(lst,i) for i in set(lst)}

    print(conv_to_dict(l))  

the error as follows:
I want to convert the list into a dictionary in which values is number of times its key appears in the list

    <ipython-input-32-a4e2a975b11c> in <dictcomp>(.0)
         13     d={}
         14     print(count(lst,lst[4]))
    ---> 15     d={x:count(lst,i) for i in set(lst)}
         16 
         17 print(conv_to_dict(l))

    TypeError: unhashable type: 'list'
Asked By: Om Khade

||

Answers:

You’re getting that error because you’re using x (which is defined in the caller’s scope as an empty list) as the key. A list can’t be used as a dictionary key because lists are mutable and keys must be immutable. That aside, though, you don’t want a list to be the key (and certainly not x which is just an empty list), but rather the specific item that you counted, which would be i.

An easier solution is to use the Counter class:

>>> from collections import Counter
>>> Counter(l)
Counter({1: 3, 3: 2, 5: 2, 2: 1})
Answered By: Samwise

Variable x is of type list and cannot be used as dictionary keys. You probably meant i variable as the key:

l=[1,1,1,2,3,3,5,5]

def count(lst,r):
    z = 0
    for i in lst:
        if i==r:
            z+=1
    return z

def conv_to_dict(lst):
    d={i:count(lst,i) for i in set(lst)}
    return d

print(conv_to_dict(l))

Prints:

{1: 3, 2: 1, 3: 2, 5: 2}

Note: There’s collections.Counter for that, as stated in @Samwise’s answer

Answered By: Andrej Kesely
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.