Skip to content Skip to sidebar Skip to footer

Python Error: Unhashable Type: 'list'

I started learning Python few weeks ago (with no previous knowledge of it nor programming). I want to create a definition which will for given dictionary as an argument return a tu

Solution 1:

You are trying to use the whole keys list as a key:

values.append(dict[keys])

Perhaps you meant to use dict[key] instead? A list is a mutable type, and cannot be used as a key in a dictionary (it could change in-place making the key no longer locatable in the internal hash table of the dictionary).

Alternatively, loop over the .items() sequence:

for key, value in dct.items():
    keys.append(key)
    values.append(value)

Please don't use dict as a variable name; you are shadowing the built-in type by doing that.

Solution 2:

Another simpler (less chance for bugs) way to write your function

defrun(my_dict):
    returnzip(*my_dict.items())

Solution 3:

Martijn's answer is correct but also note that your original sample does more work than it needs to. dict.keys() and dict.values() both return lists and there is no reason to recreate them. The code could be:

def run(my_dict):
    return my_dict.keys(), my_dict.values()

print run({"a": 1, "b": 2, "c": 3, "d": 4})

Post a Comment for "Python Error: Unhashable Type: 'list'"