Select Page

How to Solve Python TypeError: unhashable type: ‘slice’

by | Programming, Python, Tips

In Python, a dictionary is stores data in key:value pairs. Python 3.7 dictionaries are ordered data collections; in Python 3.6 and previous dictionaries are unordered. You cannot perform a slice on a Python dictionary like a list. Dictionaries can have custom key values and are not indexed from zero. If you try to slice a dictionary as if it were a list, you will raise the error “TypeError: unhashable type: ‘slice'”

This tutorial will go through the error in detail, and we will go through an example scenario of the error and learn to solve it.


TypeError: unhashable type: ‘slice’

What Does TypeError Mean?

TypeError occurs whenever you try to perform an illegal operation for a specific data type object. For example, if you try to iterate over an object that is not iterable, like an integer, you will raise the error: TypeError: ‘int’ object is not iterable.

What Does Unhashable Mean?

By definition, a dictionary key needs to be hashable. When we add a new key:value pair to a dictionary, the Python interpreter generates a hash of the key. A hash value is an integer Python uses to compare dictionary keys while looking at a dictionary. We can only hash particular objects in Python, like string or integers but not slice.

A slice is a subset of a sequence such as a string, a list or a tuple. Slices were specifically made unhashable, so an error would raise if attempting to slice-assign to a dictionary. Let’s look at an example of hashing a string and a slice using the hash() function.

string = "research scientist"

slice_ = slice(0,10)
-2741083802299845414

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

TypeError: unhashable type: 'slice'

The error tells us that you cannot get the hash of a slice. Dictionary keys need to be hashable. Therefore if you use a slice as a key to a dictionary, you will raise the TypeError: unhashable type: ‘slice’.

Similarly, if you try to create an item in a dictionary using a dictionary as a key, you will raise the error TypeError: unhashable type: ‘dict’.

Let’s look at an example scenario to recreate the error in your code.

Example: Slicing a Dictionary

Let’s write a program that displays the information about the fundamental particle, the electron. To start, you will define a dictionary to store data about the electron:

particle ={

"name": "electron",

"mass": "0.51",

"charge": -1,

"spin" : 1/2

}

The program stores the electron’s name, mass, charge, and spin. You want only to see the name, mass, and charge. You can try to use slicing to retrieve the first three items in the particle dictionary:

values_of_interest = particle[:3]

print(values_of_interest)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
1 values_of_interest = particle[:3]

TypeError: unhashable type: 'slice'

The error occurs because you cannot use slices to retrieve items like we can with a list

Solution

Data in dictionaries are stored in key:value pairs. To solve this problem, you must specify the appropriate key names in the dictionary. You can iterate over a dictionary using items() and use the enumerate() function in a for loop to ensure you only print out the first three values in the dictionary:

for i, item in enumerate(particle.items()):
    if i ≺ 3:
        print(item)
('name', 'electron')

('mass', '0.51')

('charge', -1)

The code runs successfully and prints the first three items in the dictionary. The enumerate() function gives us an integer value that increments by one after every loop. You can use if i < 3 to end the loop after three iterations.

You can also individually access each value and print the values to the console as follows:

name = particle["name"]

mass = particle["mass"]

charge = particle["charge"]

print("Name of particle:  "+name)

print("Mass of particle: "+ mass + " MeV")

print("Charge of particle: " + charge)
Name of particle:  electron

Mass of particle: 0.51 MeV

Charge of particle: -1

The above code specifies the appropriate key name for each value you want to extract. Note that for the numerical values, you need to convert them to string if you’re going to concatenate them to other strings to print. If you do not convert the numerical values to type string, you will raise the error: TypeError: can only concatenate str (not “int”) to str.

Summary

Congratulations on reading to the end of this tutorial. The error “TypeError: unhashable type: ‘slice’” occurs when you try to access items from a dictionary using slicing.

Hash values are used in Python to compare dictionary keys, and we can only use hashable objects as keys for a dictionary.

Slice is not a hashable object, and therefore it cannot be used as a key to a dictionary. To solve this error, specify the appropriate key names for the values you want or use an iterable object like items() and iterate over the items in the dictionary.

For further reading on TypeErrors related to unhashable objects, go to the article: How to Solve Python TypeError: unhashable type: ‘list’.

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

Have fun and happy researching!

Research Scientist at Moogsoft | + posts

Suf is a research scientist at Moogsoft, specializing in Natural Language Processing and Complex Networks. Previously he was a Postdoctoral Research Fellow in Data Science working on adaptations of cutting-edge physics analysis techniques to data-intensive problems in industry. In another life, he was an experimental particle physicist working on the ATLAS Experiment of the Large Hadron Collider. His passion is to share his experience as an academic moving into industry while continuing to pursue research. Find out more about the creator of the Research Scientist Pod here and sign up to the mailing list here!