1

I understand that set keys are immutable, hence data types like lists are not eligible for being a key in the set. In the example shown below why can a tuple not work as a key if a dictionary is present inside the tuple? Can somebody help me with an explanation?

x= (1,{'a':1})
y= (1,2)
print(type(x),type(y))

# piece of code which is not giving me an error is below
set1 = {x,'INDIA'}

# set 2 can be created in similar manner without an error
set2 = {y,'INDIA'}

set2
Yogesh
  • 1,384
  • 1
  • 12
  • 16

2 Answers2

0

If it were possible, think of this situation:
x[1] is refers to the dict, which is a mutable object.
If elsewhere in you program someone holds a reference to that dict and modifies it, the next time you'll use x it will have a "different value" (so e.g., won't belong in the set anymore).

x = (1, {'a':1})
print(x)
x[1]['a'] = 'BANANA'
print(x)

Output:

(1, {'a': 1})
(1, {'a': 'BANANA'})
Adam.Er8
  • 12,675
  • 3
  • 26
  • 38
  • x is a tuple, hence immutable. Having a mutable item in it does not make it mutable.https://stackoverflow.com/questions/9755990/why-can-tuples-contain-mutable-items – Yogesh Jan 23 '22 at 15:29
  • @Yogesh yea that's true, `x[1]` is always the same `x[1]`, changing my wording to simply show why this is a problem if it were allowed. – Adam.Er8 Jan 24 '22 at 13:07
0

A tuple can only serve as a key if all elements of the tuple can serve as a key. A dict cannot serve as a key (because it is mutable).

The more technical answer here is that dict keys must be hashable, and that tuples are only hashable if their individual elements are hashable.

dshin
  • 2,354
  • 19
  • 29