user36729 user36729 - 1 month ago 5
Python Question

Tuple list as key of dictionary in Python

I have a tuple list, File2, that its value is as below:

(1,2,[3,4],2)
(3,5,[2,3,4,5,6,7],3)


I also have data frame that has a column named "Count" and I want to build a dictionary that have my tuple list as key and "Count" column as value:

File3 = dict(zip(File2,df.Count))


But I am getting this error:

unhashable type: 'list'


Could you please tell me how can I solve this issue?

Answer

[3,4] in (1,2,[3,4],2) is a list. Lists aren't hashable, and only hashable objects may be the keys of dictionaries. To turn all lists into tuples, you can write a function like

def make_tuples(l):
    return tuple(make_tuples(i) if isinstance(i,list) else i for i in l)

The above fails if there is a tuple that contains a tuple that contains a list. That's probably not going to come up, but in that case do

from collections.abc import Sequence
def make_tuples(l):
    return tuple(make_tuples(i) if isinstance(i, Sequence) else i for i in l)
Comments