Why are nested dictionaries allowed in Python, while nested sets are disallowed?
One can nest dictionaries and change the sub-dictionaries on the fly, as the following demonstrates:
In [1]: dict1 = {'x':{'a':1, 'b':2}, 'y':{'c':3}}
In [2]: dict2 = {'x':{'a':1, 'b':2}, 'y':{'c':3}}
In [3]: dict1 == dict2
Out[3]: True
In [4]: dict2['x'] = {'d':4}
In [5]: dict1 == dict2
Out[5]: False
On the other hand, if you try to put a set within a set you get an error saying that it can't be done since sets are an "unhashable type":
In [6]: set([set(['a'])])
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-8-8e7d044eec15> in <module>()
----> 1 set([set(['a'])])
TypeError: unhashable type: 'set'
But this doesn't make sense since dictionaries are unhashable too,
In [7]: hash({'a':1})
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-11-44def9788331> in <module>()
----> 1 hash({'a':1})
TypeError: unhashable type: 'dict'
Of course, one can put a frozenset within a set,
In [8]: set([frozenset(['a'])])
Out[8]: {frozenset({'a'})}
but then you can't later change the internals of the nested frozenset like you could for the nested dictionaries.
According to what I've found, set
and dict
are both implemented with hash tables under the hood, so I don't see why it would be allowed in one case but not the other.