|
|
Log in / Subscribe / Register

Hashable mappings

Hashable mappings

Posted Dec 5, 2025 11:45 UTC (Fri) by iabervon (subscriber, #722)
Parent article: A "frozen" dictionary for Python

I'm looking forward to being able to check whether two unordered collections of mappings whose keys and values are strs are equivalent without a huge hassle. The code we've needed to consider [{"t": "a", "n": "b"}, {"t": "x", "n": "y"}] the same as both [{"t": "x", "n": "y"}, {"t": "a", "n": "b"}] and [{"n": "b", "t": "a"}, {"n": "y", "t": "x"}] (decoded from JSON) has been quite a pain. There wasn't a way to have a value built out of standard library data structures that can be accessed as expected and also makes these compare equal.

Next, I want a flag to json.loads() that causes it to return hashable values instead of mutable ones (without the caller needing to know how to accomplish that).


to post comments

Hashable mappings

Posted Dec 6, 2025 0:49 UTC (Sat) by AdamW (subscriber, #48457) [Link] (2 responses)

Huh. I just read the PEP, and that's in interesting detail.

It says frozendicts will be ordered, but hashes and comparisons will not care about the order.

So frozendict({"a": "b", "c": "d"}) and frozendict({"c": "d", "a": "b"}) will have the same hash and compare as equal, but they're not really the same?

I don't know how I feel about that!

Hashable mappings

Posted Dec 6, 2025 5:02 UTC (Sat) by NYKevin (subscriber, #129325) [Link]

They are "not really the same" in the sense that, if you iterate over them, you'll observe two different orders. In all other respects, they're functionally identical.

Whether this is a problem is debatable, but it is also moot. Non-frozen dicts have behaved this way forever, so making frozendict behave differently would be pretty terrible language design.

Hashable mappings

Posted Dec 6, 2025 5:23 UTC (Sat) by iabervon (subscriber, #722) [Link]

It's already the case that {"a": "b", "c": "d"} and {"c": "d", "a": "b"} compare as equal, but are distinguishable with respect to the order that iterators visit the items.

The history is that the iterator order used to be unpredictable, so the same object might give different orders when traversed multiple times and objects constructed by adding the items in different order might give the same order when traversed multiple times. However, a more recent implementation of dict started to traverse the items in the order the keys were first added, just because that was more convenient, and then the language changed to guarantee this. Of course, that meant that there was now something you could reliably determine about dicts that wasn't included in the equality rules that had always existed.


Copyright © 2026, Eklektix, Inc.
Comments and public postings are copyrighted by their creators.
Linux is a registered trademark of Linus Torvalds