while creating a dictionary: typeerror: unhashable type: 'dict'

  • Last Update :
  • Techknowledgy :

You're trying to use a dict as a key to another dict or in a set. That does not work because the keys have to be hashable. As a general rule, only immutable objects (strings, integers, floats, frozensets, tuples of immutables) are hashable (though exceptions are possible). So this does not work:

>>> dict_key = {"a": "b"}
>>> some_dict[dict_key] = True
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'dict'

To use a dict as a key you need to turn it into something that may be hashed first. If the dict you wish to use as key consists of only immutable values, you can create a hashable representation of it like this:

>>> key = frozenset(dict_key.items())

Now you may use key as a key in a dict or set:

>>> some_dict[key] = True >>>
   some_dict {
      frozenset([('a', 'b')]): True
   }

If the dict you wish to use as key has values that are themselves dicts and/or lists, you need to recursively "freeze" the prospective key. Here's a starting point:

def freeze(d):
   if isinstance(d, dict):
   return frozenset((key, freeze(value)) for key, value in d.items())
elif isinstance(d, list):
   return tuple(freeze(value) for value in d)
return d

A possible solution might be to use the JSON dumps() method, so you can convert the dictionary to a string ---

import json

a = {
   "a": 10,
   "b": 20
}
b = {
   "b": 20,
   "a": 10
}
c = [json.dumps(a), json.dumps(b)]

set(c)
json.dumps(a) in c

Output -

set(['{"a": 10, "b": 20}'])
True
def frozendict(d: dict):
   return frozenset(d.keys()), frozenset(d.values())

This happened to me because I was thinking in Typescript, and tried to set a python dictionary up like this:

thing = {
   'key': 'value'
}
other_thing = {
   'other_key': 'other_value'
}
my_dictionary = {
   thing,
   other_thing
}

Then I tried:

my_dictionary = {
   thing: thing,
   other_thing: other_thing
}

What ended up working was...

my_dictionary = {
   'thing': thing,
   'other_thing': other_thing
}

I was facing the issue while converting into set() by mistake.

my_dict = {
   'a': 'alpha',
   'b': 'beta'
}
conv = set(my_dict)

TypeError: unhashable type: 'dict'

Suggestion : 2

Last updated: Apr 20, 2022

Copied!#👇️ using dictionary as a key in a dictionary
#⛔️ TypeError: unhashable type: 'dict'
my_dict = {
   'name': 'Alice',
   {
      'country': 'Austria'
   }: 'address'
}

#👇️ using dictionary as an element in a set
#⛔️ TypeError: unhashable type: 'dict'
my_set = {
   {
      'name': 'Alice'
   }
}
Copied!my_key = {
   'country': 'Austria'
}
key = frozenset(my_key.items())
print(key) #👉️ frozenset({
   ('country', 'Austria')
})

my_dict = {
   'name': 'Alice',
   key: 'address'
}

#👇️ when you have to access the key
print(my_dict[frozenset(my_key.items())]) #👉️ 'address'
Copied!
   import json

#👇️ convert dictionary to JSON string
my_json = json.dumps({
   'country': 'Austria'
})

my_dict = {
   'name': 'Alice',
   my_json: 'address'
}
print(my_dict) #👉️ {
   'name': 'Alice',
   '{"country": "Austria"}': 'address'
}

#👇️ when you have to access the key in the dictionary
print(my_dict[json.dumps({
   'country': 'Austria'
})]) #👉️ address
Copied!print(hash('hello')) #👉️ - 1210368392134373610

#⛔️ TypeError: unhashable type: 'dict'
print(hash({
   'name': 'Alice'
}))
Copied!my_dict = {
   'name': 'Alice'
}

my_dict['name'] = 'Bob'

print(my_dict) #👉️ {
   'name': 'Bob'
}
Copied!my_dict = {'name': 'Alice'}

print(type(my_dict))  # 👉️ <class 'dict'>
print(isinstance(my_dict, dict))  # 👉️ True

my_str = 'hello'

print(type(my_str))  # 👉️ <class 'str'>
print(isinstance(my_str, str))  # 👉️ True

Suggestion : 3

Last Updated On September 16, 2021 By Anmol Lohana

drinks = [{
      "name": "Soda",
      "left": 3
   },
   {
      "name": "Beer",
      "left": 7
   },
   {
      "name": "Wine",
      "left": 9
   }
]
left_more_than_three = {}

for d in drinks:
   if d["left"] > 3:
   left_more_than_three[d] = d["left"]
print("More than 3 " + d["name"] + "are left.")

print(left_more_than_three)
drinks = [{
      "name": "Soda",
      "left": 3
   },
   {
      "name": "Beer",
      "left": 7
   },
   {
      "name": "Wine",
      "left": 9
   }
]
left_more_than_three = {}

for d in drinks:
   if d["left"] > 3:
   left_more_than_three[d["name"]] = d["left"]
print("More than 3 " + d["name"] + "are left.")

print(left_more_than_three)

Suggestion : 4

The TypeError: unhashable type: ‘dict’ error happens when you try to use a dict as a hash argument when adding as a key in another dict or in a set. The dict is an unhashable object that you’ve been trying to hash. The python unhashable type dict is not allowed in set or dict key. The dictionary or set hashes the object and uses the hash value as a primary reference to the key. Else, the error TypeError: unhashable type: ‘dict’ will be thrown in python.,The error TypeError: unhashable type: ‘dict’ will be shown as below the sack trace.,The dictionary can not be added in Set object. The dictionary is not an immutable object. The dictionary is to be converted to tuple before storing in Python Set. The immutable objects can be stored in Set. This will resolve the error TypeError: unhashable type: ‘dict’,The dictionary is an unhashable object. Create a dictionary object in python. Add the dictionary object in a set object. Or, add the dictionary object as one of the key in another dictionary. Since the unhashable object is not permitted in set or dictionary, the error will be thrown

The error TypeError: unhashable type: ‘dict’ will be shown as below the sack trace.

Traceback (most recent call last):
  File "/Users/python/Desktop/test.py", line 2, in <module>
    b = {a:1, 2:3}
TypeError: unhashable type: 'dict'
[Finished in 0.1s with exit code 1]

test.py

a = {
   1: 1,
   2: 2,
   3: 3
}
b = {
   a: 1,
   2: 3
}
print b

Output

Traceback (most recent call last):
  File "/Users/python/Desktop/test.py", line 2, in <module>
    b = {a:1, 2:3}
TypeError: unhashable type: 'dict'
[Finished in 0.1s with exit code 1]

Solution

a = tuple({
   1: 1,
   2: 2,
   3: 3
})
b = {
   a,
   2
}
print b

Suggestion : 5

If you are handling dictionaries containing keys and values, you might have encountered the program error "typeerror unhashable type 'dict'". This means that you are trying to hash an unhashable object. In simple terms, this error occurs when your code tries to hash immutable objects such as a dictionary. The solution to this problem is to convert the dictionary into something that is hashable.,To fix this error, you can convert the dictionary into a hashable object like 'tuple' and then use it as a key for a dictionary as shown below,indentationerror: unindent does not match any outer indentation level in Python,All the site contents are Copyright © www.stechies.com and the content authors. All rights reserved. All product names are trademarks of their respective companies. The site www.stechies.com is in no way affiliated with SAP AG. Every effort is made to ensure the content integrity. Information used on this site is at your own risk. The content on this site may not be reproduced or redistributed without the express written permission of www.stechies.com or the content authors.

Error Example:

# Pyton Program
my_dictionary = {
   'Red': 'Apple',
   'Green': 'Mango',
   {
      'Red': 'Apple',
      'Green': 'Mango'
   }: 'Banana'
}
print('Dictionary :', my_dictionary)

Output:

Traceback (most recent call last):
File "pyprogram.py", line 1, in <module>
my_dictionary = {'Red':'Apple','Green':'Mango',{'Red':'Apple','Green':'Mango'}:'Banana'}
TypeError: unhashable type: 'dict'

Correct Code:

# Python Program
my_dictionary = {
   'Red': 'Apple',
   'Green': 'Mango',
   tuple({
      'Red': 'Apple',
      'Green': 'Mango'
   }): 'Banana'
}
print('Dictionary :', my_dictionary)

Suggestion : 6

In Python, a dictionary is stores data in key:value pairs. Python 3.7 dictionaries are ordered data collections; Python 3.6 and previous dictionaries are unordered. In a Python dictionary, all keys must be hashable. If you try to use the unhashable key type ‘dict’ when adding a key or retrieving a value, you will raise the error “TypeError: unhashable type: ‘dict'”.,Congratulations on reading to the end of this tutorial! The error “TypeError: unhashable type: ‘dict'” occurs when you try to create an item in a dictionary using a dictionary as a key. Python dictionary is an unhashable object. Only immutable objects like strings, tuples, and integers can be used as a key in a dictionary because they remain the same during the object’s lifetime. ,The error occurs because we attempt to generate a dictionary key with another dictionary. The value of f is a dictionary from the list of fruits. If we try to add something to the fruits_more_than_three dictionary, we add a dictionary as a key. When we execute the if statement on apple, the interpreter sees:,To solve this error, ensure you use hashable objects when creating or retrieving an item from a dictionary.

1._
# Example dictionary

dictionary = {

   "name": "John",

   "age": 28

}

print(type(dictionary))

print(hash(dictionary))
# Example dictionary
 
dictionary = {

"name":"John", 

"age":28

}

print(type(dictionary))

print(hash(dictionary))
TypeError Traceback(most recent call last)
1 print(hash(dictionary))

TypeError: unhashable type: 'dict'

Example: Generating a Dictionary Key with Another Dictionary

# Define list of dictionaries containing several fruits and amounts of each

fruits = [{
      "name": "apples",
      "left": 4
   },
   {
      "name": "pears",
      "left": 9
   },
   {
      "name": "bananas",
      "left": 3
   }
]
5._
TypeError Traceback(most recent call last)
1
for f in fruits:
   2
if f["left"]≻ 3:
   3 fruits_more_than_three[f] = f["left"]
4 print(f 'There are more than three of {f["name"]} left')
5

TypeError: unhashable type: 'dict'

The error occurs because we attempt to generate a dictionary key with another dictionary. The value of f is a dictionary from the list of fruits. If we try to add something to the fruits_more_than_three dictionary, we add a dictionary as a key. When we execute the if statement on apple, the interpreter sees:

fruits_more_than_three[{
   "name": "apples",
   "left": 4
}] = 4

Suggestion : 7

Vinay KhatriLast updated on July 21, 2022

Error Example 1: Try to hash a dictionary using hash() function

requirements = {
   "LED": 100,
   "100m Wire": 40,
   "Switches": 100,
   "Motors": 15,
   "Fuse": 250
}
#
try to hash the requirements dictionary(Error)
hash(requirements)

Output

Traceback(most recent call last):
   File "main.py", line 8, in
hash(requirements)
TypeError: unhashable type: 'dict'
3._
dict1 = {
   1: "a"
}

# use dict1 as a key
for dict2
dict2 = {
   dict1: "b"
}
#error

To solve the above example, we need to ensure that we are not using a dictionary object as key data for our priority dictionary. Instead of using the priority[item] = item["Quantity"] statement we should use priority[item["Name"]] = item["Quantity"] .

requirement = [{
      "Name": "LEDs",
      "Quantity": 250
   },
   {
      "Name": "Electric Tape",
      "Quantity": 500
   },
   {
      "Name": "Fuse",
      "Quantity": 100
   },
   {
      "Name": "Moters",
      "Quantity": 10
   },
   {
      "Name": "Switches",
      "Quantity": 100
   },
   {
      "Name": "Wire(100M)",
      "Quantity": 500
   }
]

# priority dictionary
priority = dict()

for item in requirement:
   # item with quantity greater than 200
if item["Quantity"] > 200:
   priority[item["Name"]] = item["Quantity"] #solved

print("The priority items are")
print(priority)
dict1 = {
   1: "a"
}

# use dict1 as a key
for dict2
dict2 = {
   dict1: "b"
}
#error