[python] Python dictionary : TypeError: unhashable type: 'list'

I'm having troubles in populating a python dictionary starting from another dictionary.

Let's assume that the "source" dictionary has string as keys and has a list of custom objects per value.

I'm creating my target dictionary exactly as I have been creating my "source" dictionary how is it possible this is not working ?

I get

TypeError: unhashable type: 'list'

Code :

aTargetDictionary = {}
for aKey in aSourceDictionary:
    aTargetDictionary[aKey] = []
    aTargetDictionary[aKey].extend(aSourceDictionary[aKey])

The error is on this line : aTargetDictionary[aKey] = []

This question is related to python hash dictionary

The answer is


The error you gave is due to the fact that in python, dictionary keys must be immutable types (if key can change, there will be problems), and list is a mutable type.

Your error says that you try to use a list as dictionary key, you'll have to change your list into tuples if you want to put them as keys in your dictionary.

According to the python doc :

The only types of values not acceptable as keys are values containing lists or dictionaries or other mutable types that are compared by value rather than by object identity, the reason being that the efficient implementation of dictionaries requires a key’s hash value to remain constant


It works fine : http://codepad.org/5KgO0b1G, your aSourceDictionary variable may have other datatype than dict

aSourceDictionary = { 'abc' : [1,2,3] , 'ccd' : [4,5] }
aTargetDictionary = {}
for aKey in aSourceDictionary:
        aTargetDictionary[aKey] = []
        aTargetDictionary[aKey].extend(aSourceDictionary[aKey])
print aTargetDictionary

This is indeed rather odd.

If aSourceDictionary were a dictionary, I don't believe it is possible for your code to fail in the manner you describe.

This leads to two hypotheses:

  1. The code you're actually running is not identical to the code in your question (perhaps an earlier or later version?)

  2. aSourceDictionary is in fact not a dictionary, but is some other structure (for example, a list).


As per your description, things don't add up. If aSourceDictionary is a dictionary, then your for loop has to work properly.

>>> source = {'a': [1, 2], 'b': [2, 3]}
>>> target = {}
>>> for key in source:
...   target[key] = []
...   target[key].extend(source[key])
... 
>>> target
{'a': [1, 2], 'b': [2, 3]}
>>> 

You can also use defaultdict to address this situation. It goes something like this:

from collections import defaultdict

#initialises the dictionary with values as list
aTargetDictionary = defaultdict(list)

for aKey in aSourceDictionary:
    aTargetDictionary[aKey].append(aSourceDictionary[aKey])

Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to hash

php mysqli_connect: authentication method unknown to the client [caching_sha2_password] What is Hash and Range Primary Key? How to create a laravel hashed password Hashing a file in Python PHP salt and hash SHA256 for login password Append key/value pair to hash with << in Ruby Are there any SHA-256 javascript implementations that are generally considered trustworthy? How do I generate a SALT in Java for Salted-Hash? What does hash do in python? Hashing with SHA1 Algorithm in C#

Examples related to dictionary

JS map return object python JSON object must be str, bytes or bytearray, not 'dict Python update a key in dict if it doesn't exist How to update the value of a key in a dictionary in Python? How to map an array of objects in React C# Dictionary get item by index Are dictionaries ordered in Python 3.6+? Split / Explode a column of dictionaries into separate columns with pandas Writing a dictionary to a text file? enumerate() for dictionary in python