Do dictionaries in Python have a single meaning in the editor?

It was suggested in this question that invoking the correspondence in a dictionary would be a good way to store it in another dictionary. This will depend on whether the replica is the same regardless of how the keys are ordered. Is this the case?

PS. the most elegant solution to the original problem was actually using frozenset

+2


source to share


3 answers


No, the order in which keys are added to the dictionary can affect the internal data structure. When two elements have the same hash value and end up in the same bucket, then the order they add to the dictionary matters.



>>> (1).__hash__()
1
>>> (1 << 32).__hash__()
1
>>> repr({1: 'one', 1 << 32: 'not one'})
"{1: 'one', 4294967296L: 'not one'}"
>>> repr({1 << 32: 'not one', 1: 'one'})
"{4294967296L: 'not one', 1: 'one'}"

      

+7


source


This is not the case - the order of the keys is arbitrary.



If you want to use a dictionary as a key, you must convert it to a fixed form (for example, a sorted tuple). Of course this will not work for dictionaries with invalid values.

+2


source


If you want to store the dictionary in another dictionary, you don't need to do any conversions first. If you want to use a dictionary as a key for another dictionary, you need to convert it, ideally, to a sorted key / value tuple.

0


source







All Articles