Python "TypeError: unhashable type: ‘dict’ " occurs when we use a dictionary as a key in another dictionary or as an element in a collection.
To resolve this error, you need to use frozenset
instead, or convert the dictionary to a JSON string before using it as a key.
The error occurs when we use a dictionary as a key in another dictionary.
# ????️ using dictionary as a key in a dictionary # ⛔️ TypeError: unhashable type: 'dict' my_dict = {'name': 'Jiyik', {'country': 'China'}: 'address'}
Or when we use a dictionary as an element in a set
object.
# ????️ 使用字典作为集合中的元素 # ⛔️ TypeError: unhashable type: 'dict' my_set = {{'name': 'Jiyik'}}
We cannot use a dictionary as a key in a dictionary or an element in a collection because dictionary objects are mutable and unhashable.
Convert the dictionary to a JSON string to resolve the error
One way to resolve this error is to convert the dictionary to a JSON string before using it as a key.
import json # ????️ 将字典转换为 JSON 字符串 my_json = json.dumps({'country': 'China'}) my_dict = {'name': 'Jiyik', my_json: 'address'} print(my_dict) # ????️ {'name': 'Jiyik', '{"country": "China"}': 'address'} # ????️ 当你必须访问字典中的键时 print(my_dict[json.dumps({'country': 'Austria'})]) # ????️ address
json.dumps
Method converts a Python object into a JSON-formatted string. This works because strings are immutable and hashable.
In contrast, the json.loads
method parses a JSON string into a native Python object, such as my_dict = json.loads(my_json_str)
.
Using frozenset to resolve errors
Another way to resolve errors is to use frozenset
.
my_key = {'country': 'China'} key = frozenset(my_key.items()) print(key) # ????️ frozenset({('country', 'China')}) my_dict = {'name': 'Jiyik', key: 'address'} # ????️ 当我们必须访问 key 时 print(my_dict[frozenset(my_key.items())]) # ????️ 'address'
dict.items
Method returns a new view of dictionary items ((key, value) pairs).
# ????️ dict_items([('name', 'jiyik'), ('age', 30)]) print({'name': 'jiyik', 'age': 30}.items())
We use the dictionary's items to create a frozenset
that we can use as a key in the dictionary (as well as an element in another set).
frozenset
is an immutable version of a Python collection object, so it can be used as a key in a dictionary or as an element in another collection.
Please note that we must use the same method to access the keys in the dictionary.
We can store the result of calling frozenset(my_key.items())
in a variable and reuse the frozenset when setting or accessing keys in the dictionary.
Convert dictionary to tuple to resolve error
Another way to resolve the error is to convert dictionary to tuple.
dict_key = {'id': 1, 'country': 'China'} # ✅ 转换为元组 my_tuple = tuple(dict_key) print(my_tuple) # ????️ ('id', 'country') my_dict = {'name': 'Jiyik', my_tuple: 'address'} print(my_dict) # ????️ {'name': 'Jiyik', ('id', 'country'): 'address'} # ????️ 当你必须访问字典中的键时 print(my_dict[my_tuple]) # ????️ address
When converting a dictionary to a tuple, the tuple only contains the keys of the dictionary.
Tuples are immutable, so a tuple containing a dictionary key can safely be used as a key in another dictionary.
Using one dictionary as a value in another dictionary
We cannot use a dictionary as a key in another dictionary, but we can use a dictionary as a value.
dict_value = {'id': 1, 'country': 'China'} my_dict = {'name': 'Jiyik', 'data': dict_value} # ????️ {'name': 'Jiyik', 'data': {'id': 1, 'country': 'China'}} print(my_dict) print(my_dict['data']) # ????️ {'id': 1, 'country': 'China'}
We set a dictionary to a value in another dictionary.
This is allowed because the limit does not apply to dictionary values.
Add all key-value pairs of one dictionary to another dictionary
If you need to add all key-value pairs of one dictionary to another dictionary, you can use a for loop.
another_dict = {'id': 1, 'country': 'China'} my_dict = {'name': 'Jiyik'} for key, value in another_dict.items(): my_dict[key] = value # ????️ {'name': 'Jiyik', 'id': 1, 'country': 'China'} print(my_dict)
dict.items
Method returns a new view of dictionary items ((key, value) pairs).
my_dict = {'id': 1, 'name': 'Jiyik'} # ????️ dict_items([('id', 1), ('name', 'Jiyik')]) print(my_dict.items())
In each iteration, we set the key-value pairs to another dictionary.
Hashable vs. Unhashable Objects in Python
Most of the immutable built-in objects in Python are hashable, while mutable objects are not hashable.
If an object is hashable, then it can be used as a key in a dictionary and an element in a collection because these data structures use hash values internally.
Hashable objects include - str, int, bool, tuple, frozenset.
Unhashable objects include - list, dict, set.
Checking if an object is hashable
Please note that tuples and frozen sets are hashable only if their elements are hashable.
We can check if an object is hashable by passing it to the built-in
hash() function. <pre class='brush:php;toolbar:false;'>print(hash(&#39;jiyik.com&#39;)) # ????️ 4905958875846995527
# ⛔️ TypeError: unhashable type: &#39;dict&#39;
print(hash({&#39;name&#39;: &#39;Jiyik&#39;}))</pre>
The hash function returns the hash value of the passed in object (if any).
Hash values are integers used to compare dictionary keys during dictionary lookups.
!> The hash value of a hashable object never changes during its lifetime. This is why most immutable objects are hashable, while mutable objects are not hashable.
Objects like dictionaries are mutable because the contents of the dictionary can change.
my_dict = {'name': 'Fql'} my_dict['name'] = 'Jiyik' print(my_dict) # ????️ {'name': 'Jiyik'}
On the other hand,
fronzenset and tuple objects containing primitive values are immutable (and hashable). Dictionaries are indexed by keys, which can be any immutable type, such as strings or numbers.
If thefronzenset
or tuple contains a mutable object (such as a list), it cannot be used as a key in a dictionary or an element in a set. If we are not sure what type of object a variable stores, please use the
function. <pre class='brush:php;toolbar:false;'>my_dict = {&#39;name&#39;: &#39;Jiyik&#39;}
print(type(my_dict)) # ????️ <class &#39;dict&#39;>
print(isinstance(my_dict, dict)) # ????️ True
my_str = &#39;jiyik.com&#39;
print(type(my_str)) # ????️ <class &#39;str&#39;>
print(isinstance(my_str, str)) # ????️ True</pre>
The function returns the type of the object. <p>If the object passed in is an instance or subclass of the passed class, the <code>isinstance
function returns True.
The above is the detailed content of How to solve TypeError:unhashable type:'dict' error in Python. For more information, please follow other related articles on the PHP Chinese website!

InPython,youappendelementstoalistusingtheappend()method.1)Useappend()forsingleelements:my_list.append(4).2)Useextend()or =formultipleelements:my_list.extend(another_list)ormy_list =[4,5,6].3)Useinsert()forspecificpositions:my_list.insert(1,5).Beaware

The methods to debug the shebang problem include: 1. Check the shebang line to make sure it is the first line of the script and there are no prefixed spaces; 2. Verify whether the interpreter path is correct; 3. Call the interpreter directly to run the script to isolate the shebang problem; 4. Use strace or trusts to track the system calls; 5. Check the impact of environment variables on shebang.

Pythonlistscanbemanipulatedusingseveralmethodstoremoveelements:1)Theremove()methodremovesthefirstoccurrenceofaspecifiedvalue.2)Thepop()methodremovesandreturnsanelementatagivenindex.3)Thedelstatementcanremoveanitemorslicebyindex.4)Listcomprehensionscr

Pythonlistscanstoreanydatatype,includingintegers,strings,floats,booleans,otherlists,anddictionaries.Thisversatilityallowsformixed-typelists,whichcanbemanagedeffectivelyusingtypechecks,typehints,andspecializedlibrarieslikenumpyforperformance.Documenti

Pythonlistssupportnumerousoperations:1)Addingelementswithappend(),extend(),andinsert().2)Removingitemsusingremove(),pop(),andclear().3)Accessingandmodifyingwithindexingandslicing.4)Searchingandsortingwithindex(),sort(),andreverse().5)Advancedoperatio

Create multi-dimensional arrays with NumPy can be achieved through the following steps: 1) Use the numpy.array() function to create an array, such as np.array([[1,2,3],[4,5,6]]) to create a 2D array; 2) Use np.zeros(), np.ones(), np.random.random() and other functions to create an array filled with specific values; 3) Understand the shape and size properties of the array to ensure that the length of the sub-array is consistent and avoid errors; 4) Use the np.reshape() function to change the shape of the array; 5) Pay attention to memory usage to ensure that the code is clear and efficient.

BroadcastinginNumPyisamethodtoperformoperationsonarraysofdifferentshapesbyautomaticallyaligningthem.Itsimplifiescode,enhancesreadability,andboostsperformance.Here'showitworks:1)Smallerarraysarepaddedwithonestomatchdimensions.2)Compatibledimensionsare

ForPythondatastorage,chooselistsforflexibilitywithmixeddatatypes,array.arrayformemory-efficienthomogeneousnumericaldata,andNumPyarraysforadvancednumericalcomputing.Listsareversatilebutlessefficientforlargenumericaldatasets;array.arrayoffersamiddlegro


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Zend Studio 13.0.1
Powerful PHP integrated development environment

SublimeText3 English version
Recommended: Win version, supports code prompts!
