pythonpython-3.xdictionary

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


    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'

Solution

  • 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})