In Python, a TypeError is raised when an operation or function is applied to an object of inappropriate type. One such error is the “TypeError: unhashable type: ‘set'” error. This error occurs when we try to use a set as a key in a dictionary or as an element in another set. In this tutorial, we will discuss the reasons behind this error and how to fix it.
Understanding the TypeError: unhashable type: 'set'
error
In Python, hashable types are those which have a hash value that remains constant throughout its lifetime. Hash values are unique identifiers assigned to objects by Python’s built-in hash()
function. These hash values are used to quickly compare and access objects in dictionaries and sets.
On the other hand, unhashable types are those which do not have a constant hash value and cannot be used as keys in dictionaries or elements in sets. Examples of unhashable types include lists, sets, and dictionaries themselves.
To illustrate the difference between hashable and unhashable types, consider the following example:
# Hashable type (tuple) my_tuple = (1, 2, 3) print(hash(my_tuple))
Output:
529344067295497451
# Unhashable type (set) my_set = {1, 2, 3} print(hash(my_set))
Output:
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[7], line 3 1 # Unhashable type (set) 2 my_set = {1, 2, 3} ----> 3 print(hash(my_set)) TypeError: unhashable type: 'set'
In the above example, we create a tuple my_tuple
and a set my_set
containing the same elements. When we try to hash the tuple using the built-in hash()
function, we get a unique hash value. However, when we try to hash the set, we get a TypeError
because sets are unhashable in Python. This means that we cannot use sets as keys in dictionaries or elements in other sets.
The TypeError: unhashable type: 'set'
error occurs when we try to use a set in a place that requires a hashable type, for example, as a key in a dictionary or a value in another set. This error occurs because sets are mutable, which means that their contents can be changed. In Python, only immutable objects can be used as keys in a dictionary or as elements in a set.
Introductory ⭐
- Harvard University Data Science: Learn R Basics for Data Science
- Standford University Data Science: Introduction to Machine Learning
- UC Davis Data Science: Learn SQL Basics for Data Science
- IBM Data Science: Professional Certificate in Data Science
- IBM Data Analysis: Professional Certificate in Data Analytics
- Google Data Analysis: Professional Certificate in Data Analytics
- IBM Data Science: Professional Certificate in Python Data Science
- IBM Data Engineering Fundamentals: Python Basics for Data Science
Intermediate ⭐⭐⭐
- Harvard University Learning Python for Data Science: Introduction to Data Science with Python
- Harvard University Computer Science Courses: Using Python for Research
- IBM Python Data Science: Visualizing Data with Python
- DeepLearning.AI Data Science and Machine Learning: Deep Learning Specialization
Advanced ⭐⭐⭐⭐⭐
- UC San Diego Data Science: Python for Data Science
- UC San Diego Data Science: Probability and Statistics in Data Science using Python
- Google Data Analysis: Professional Certificate in Advanced Data Analytics
- MIT Statistics and Data Science: Machine Learning with Python - from Linear Models to Deep Learning
- MIT Statistics and Data Science: MicroMasters® Program in Statistics and Data Science
🔎 Find Data Science Programs 👨💻 111,889 already enrolled
Disclaimer: Data Science Parichay is reader supported. When you purchase a course through a link on this site, we may earn a small commission at no additional cost to you. Earned commissions help support this website and its team of writers.
Let’s look at examples of the common scenarios where this error occurs.
# using a set as a key in a dictionary my_set = {1, 2, 3} my_dictionary = { "Name": "Jim", my_set: "Yes" } print(my_dictionary)
Output:
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[8], line 3 1 # using a set as a key in a dictionary 2 my_set = {1, 2, 3} ----> 3 my_dictionary = { 4 "Name": "Jim", 5 my_set: "Yes" 6 } 7 print(my_dictionary) TypeError: unhashable type: 'set'
In the above example, we’re trying to use the set my_set
as a key in the dictionary my_dictionary
. You can see that we get the TypeError: unhashable type: 'set'
.
# using a set as a an element in another set set1 = {1, 2, 3} set2 = {4, 5} # add set2 as an element in set1 set1.add(set2)
Output:
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[9], line 6 3 set2 = {4, 5} 5 # add set2 as an element in set1 ----> 6 set1.add(set2) TypeError: unhashable type: 'set'
In the above example, we’re trying to add the set set2
as an element to the set set1
. Since sets are unhashable types, we get the error TypeError: unhashable type: 'set'
.
Fixing the Error
To fix the TypeError: unhashable type: 'set'
, use a hashable type like a frozen set or a tuple instead of a set. For example, if you’re trying to use a set as a key in a dictionary, use a frozen set (or a tuple) instead. Similarly, if you’re trying to use a set as an element in another set, you can use a tuple or a frozen set instead.
A frozenset
is an immutable set in Python. It is similar to a set, but once a frozenset
is created, you cannot add or remove elements from it. However, you can perform set operations like union, intersection, and difference on frozenset
objects.
Note that you can create a frozenset
from a set using the frozenset()
constructor.
Let’s revisit the examples from above and fix those errors.
# using a frozenset as a key in a dictionary my_frozen_set = frozenset({1, 2, 3}) my_dictionary = { "Name": "Jim", my_frozen_set: "Yes" } print(my_dictionary)
Output:
{'Name': 'Jim', frozenset({1, 2, 3}): 'Yes'}
In the above example, we replaced the set my_set
with the fronzenset, my_frozen_set as a key in the dictionary. We don’t get an error on executing the above code. Notice that you can still use a set as a value in a dictionary but the keys must be hashable types.
# using a frozenset as a an element in another set set1 = {1, 2, 3} set2 = frozenset({4, 5}) # add set2 as an element in set1 set1.add(set2) print(set1)
Output:
{frozenset({4, 5}), 1, 2, 3}
In the above example, we added a fronzen set instead of a set to set1
. You can see that we don’t get the error now.
In summary, you can take the following steps to fix the TypeError: unhashable type: 'set'
error.
- Identify the code that is causing the error.
- Check if you are using a set as a key in a dictionary or as an element in a set.
- If you are using a set as a key in a dictionary or as a value in another set, consider using a frozenset or a tuple instead. Frozensets and Tuples are immutable and can be hashed.
Conclusion
The “TypeError: unhashable type: ‘set'” error occurs when we try to use a set as a key in a dictionary or as an element in a set. This error can be fixed by converting the set into an immutable object such as a frozenset or a tuple. By following the steps mentioned in this tutorial, you can easily fix this error and make your code more efficient and error-free.
You might also be interested in –