How to Solve Python TypeError: unhashable type ‘set’

by | Programming, Python, Tips

The error TypeError: unhashable type: ‘set’ occurs when trying to get a hash of a set object. For example, using a set as a key in a dictionary.

To solve this error, we can cast the set to a frozenset or a tuple, which are both hashable container objects.

This tutorial will go through the error in detail and how to solve it with the help of code examples.


TypeError: unhashable type ‘set’

What Does TypeError Mean?

TypeError occurs whenever you try to perform an illegal operation for a specific data type object. The illegal operation is hashing in this example, and the data type is set.

What Does Unhashable Mean?

By definition, a dictionary key needs to be hashable. An object is hashable if it has a hash value that remains the same during its lifetime. Hashing is an encoding process that produces a unique key used to search for data, for example, a key to find a value in a dictionary.

When we add a new key:value pair to a dictionary, the Python interpreter generates a hash of the key.

Immutable objects, objects that do not change once created, are hashable. Python objects such as list, set, and dictionary are mutable objects that are not hashable. To use a set as a key in a dictionary or an item to a set, we need to convert the set to an immutable object like a tuple or a frozenset.

Example #1: Adding a Set to a Set

Let’s look at an example where we attempt to add two sets to another set:

x, y = {2, 7, 11}, {4, 1, 9}

print(set([x, y]))

The items x and y are sets in another set object. Let’s run the code to see what happens:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
      1 x, y = {2, 7, 11}, {4, 1, 9}
      2 
----≻ 3 print(set([x, y]))

TypeError: unhashable type: 'set'

We can think of a Python set as a dictionary with only keys: therefore, set objects can contain immutable elements. If we try to use sets as elements in a set, we are attempting to use mutable elements, which will throw the TypeError.

Solution

We can cast each set to a frozenset using the built-in frozenset() function to solve this error. The frozenset() function takes an iterable object and returns an immutable frozen set object. We cannot add or remove elements from a frozenset once we create it. We can use the frozenset objects as elements in a set. Let’s look at the revised code:

x, y = {2, 7, 11}, {4, 1, 9}

print(set([frozenset(x), frozenset(y)]))

Let’s run the code to see the result:

{frozenset({1, 4, 9}), frozenset({2, 11, 7})}

We could also cast the set objects to tuples using the tuple() function. Tuples are also immutable container objects.

x, y = {2, 7, 11}, {4, 1, 9}

print(set([tuple(x), tuple(y)]))
{(2, 11, 7), (1, 4, 9)}

Example #2: Using a Set as a Key in a Dictionary

Let’s look at an example where we attempt to use a set as a key in a dictionary:

name_set = {"Terry", "Prue", "Cheryl"}


a_dict = {
   "Rupert": 2,
   "Biff":4,
   name_set:6
}

print(a_dict)

In the above code, the object name_set is a set containing three names. Let’s run the code to see what happens:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
      2 
      3 
----≻ 4 a_dict = {
      5    "Rupert": 2,
      6    "Biff":4,

TypeError: unhashable type: 'set'

We throw the error because a dictionary can only have hashable objects as keys, and a set is mutable and therefore unhashable.

Solution

We can cast the set to a tuple using the tuple() function to solve this error. Let’s look at the revised code:

name_set = {"Terry", "Prue", "Cheryl"}


a_dict = {
   "Rupert": 2,
   "Biff":4,
   tuple(name_set):6
}

print(a_dict)

Let’s run the code to see the result:

{'Rupert': 2, 'Biff': 4, ('Cheryl', 'Prue', 'Terry'): 6}

We could also cast the set to a frozenset using the frozen() function.

name_set = {"Terry", "Prue", "Cheryl"}


a_dict = {
   "Rupert": 2,
   "Biff":4,
   frozenset(name_set):6
}

print(a_dict)
{'Rupert': 2, 'Biff': 4, frozenset({'Cheryl', 'Prue', 'Terry'}): 6}

Summary

Congratulations on reading to the end of this tutorial! The error TypeError: unhashable type: ‘set’ occurs when you add a set to another set or use a set as a key in a dictionary. To solve this error, you must convert the set to an immutable object such as a tuple or a frozenset.

For further reading on TypeError with unhashable data types, go to the article: How to Solve Python TypeError: unhashable type: ‘numpy.ndarray’.

Go to the Python online courses page to learn more about coding in Python for data science and machine learning.

Have fun and happy researching!

Profile Picture
Senior Advisor, Data Science | [email protected] | + posts

Suf is a senior advisor in data science with deep expertise in Natural Language Processing, Complex Networks, and Anomaly Detection. Formerly a postdoctoral research fellow, he applied advanced physics techniques to tackle real-world, data-heavy industry challenges. Before that, he was a particle physicist at the ATLAS Experiment of the Large Hadron Collider. Now, he’s focused on bringing more fun and curiosity to the world of science and research online.

Buy Me a Coffee ✨