简体   繁体   中英

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 tuple consisted of two lists - one where there are only keys of dictionary, and the other where there are only values of the given dictionary. Basically the code will look like this:

"""Iterate over the dictionary named letters, and populate the two lists so that 
keys contains all the keys of the dictionary, and values contains 
all the corresponding values of the dictionary. Return this as a tuple in the end."""

def run(dict):
    keys = []
    values = []
    for key in dict.keys():
        keys.append(key)
    for value in dict.values():
        values.append(value)
    return (keys, values)


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

This code worked perfectly (it's not my solution though). But what if I do not want to use the .keys() and .values() methods? In that case, I tried using something like this, but I got "unhashable type: 'list'" error message:

def run(dict):
    keys = []
    values = []
    for key in dict:
        keys.append(key)
        values.append(dict[keys])
    return (keys, values)


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

What seems to be the problem?

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.

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

def run(my_dict):
    return zip(*my_dict.items())

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM