pythonpython-2.7hashmapfrozenset

Is it safe to use frozen set as Dict key?


It obviously works but are there cases where two sets of same elements happen to add two entries in Dict? I guess I got this condition earlier and changed my code from frozenset(...) to tuple(sorted(frozenset(...))). Can someone who knows how Dict and frozenset implementation confirm if that is required or not?


Solution

  • are there cases where two sets of same elements happen to add two entries in Dict?

    No. frozenset hashing algorithm doesn't depend on the order of the elements, only on elements themselves. Two FS'es with the same elements are equal and have equal hashes, thus satisfying both criteria for "dict identity", in other words, they are the same dict key:

    >>> a = frozenset([1,1,1,1,2,3])
    >>> b = frozenset([3,3,3,3,2,1])
    >>> {a:1, b:2}
    {frozenset([1, 2, 3]): 2}