0

A thing in python that really freaks me out is this error: TypeError: unhashable type.

Ideally i would like to have a data structure where i just use sets instead of lists so i can use the set operators like this:

a = {({1,2}, 'alpha'), ({2,3}, 'beta')}
b = {({1,2}, 'alpha')}

c = a - b # c = {({2,3}, 'beta')}

I can not even create a set that contains sets because i get the TypeError: unhashable type: set

So i try to use a list instead of a set. this way i can at least assign the values for a and b. but using the set method again to substract one set from another leads to the same error:

a = [({1,2}, 'alpha'), ({2,3}, 'beta')]
b = [({1,2}, 'alpha')]

c = list(set(a) - set(b)) # c = [({2,3}, 'beta')]

I tried it with a dictionary instead of a list, same error.

Question: How can i compare two bunches containing elements that somewhere contain sets?

Or am i thinking fundamentally wrong/ "not pythonic" and the error is rooted in the data structure itself?

Thanks for your help!

Muff

Raggamuffin
  • 699
  • 1
  • 6
  • 19

2 Answers2

3

The only thing you can do is to use frozenset for inner data (or transform sets to frozensets if it comes from outer world), as its created exactly for that.

No mutable data structure from standard library can be hashed (and probably most of implemented shouldn't), and there's simple reason for that. If you'll think how to implement hash on set/list, you'll get it fast ;)

Slam
  • 8,112
  • 1
  • 36
  • 44
  • 1
    'No mutable data structure can be hashed' is not true. you can implement `__hash__(self)` in any class (but you probably shouldn't). – hiro protagonist Dec 26 '16 at 12:23
2

you can only put immutable (or at least hashable) data in a set (or as key of a dictionary). set itself is not immutable; but frozenset is.

a similar question is here: Why aren't Python sets hashable?

a = {(frozenset((1, 2)), 'alpha'), (frozenset((2, 3)), 'beta')}
b = {(frozenset((1, 2)), 'alpha')}

c = a - b
print(c)  # -> {(frozenset({2, 3}), 'beta')}

this does now just what you want.

hiro protagonist
  • 44,693
  • 14
  • 86
  • 111