Is it safe to use a frozen set as a dict key?

Obviously this works, but are there cases where two sets of identical elements add two entries to the Dict? I guess I got this condition earlier and changed the code from frozenset(...) to tuple(sorted(frozenset(...))) . Can anyone who knows how the implementation of Dict and frozenset confirm whether this is required or not?

+7
source share
3 answers

There are times when two sets of identical elements add two entries to a dict?

No. frozenset hashing algorithm does not depend on the order of elements, only on the elements themselves. Two files with the same elements are equal and have equal hashes, thus satisfying both criteria for a β€œdictate identifier”, in other words, they are the same key 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} 
+9
source

Is it safe to use frozenset as a dict key? Yes.

According to the docs, Frozenset is healable because it is immutable. This will mean that it can be used as a dictation key, since a hash is a prerequisite for the key.

From FrozenSet Documents

The frozenset type is immutable and hashed - its contents cannot be changed after it is created; therefore, it can be used as a dictionary key or as an element of another set.

And unnecessarily, from the dictionary of documents :

... keys that can be of any immutable type


For clarification, a set (by definition), frozen or not, does not preserve order. They are stored internally, taking into account an order that is not taken into account, and with the removal of duplicate elements, so two sets built in different orders will be equivalent keys in the dictionary - they are the same.

 >>> frozenset([1,2,2,3,3]) == frozenset([3,2,1,1,1]) True 

and also,

 >>> d = {} >>> d[frozenset([1,1,2,3])] = 'hello' >>> d[frozenset([1,2,3,3])] 'hello' >>> d[frozenset([3,3,3,2,1,1,1])] 'hello' >>> d[frozenset([2,1,3])] 'hello' 
+16
source

from official documents

The frozenset type is immutable and hashed - its contents cannot be changed after it is created; , therefore, it can be used as a dictionary key or as an element of another set.

(Emphasis mine)

+7
source

Source: https://habr.com/ru/post/982618/


All Articles