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
CodePudding user response:
Well, because x is indeed mutable!
x[1] is refers to the dict, which is a mutable object.
x = (1, {'a':1})
print(x)
x[1]['a'] = 'BANANA'
print(x)
Output:
(1, {'a': 1})
(1, {'a': 'BANANA'})
CodePudding user response:
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.
