'Why is a set not taking tuple (where dictionary is an item) as a key?
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
Solution 1:[1]
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.
Solution 2:[2]
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'})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | dshin |
| Solution 2 |
