3 ms·
Good information, and well put. A small quibble: you should probably almost never use tuple(), even on recent Python: >>> tuple(dict(a=1, b=2).items())
by sago 7y ago
Good information, and well put. A small quibble: you should probably almost never use tuple(), even on recent Python:
>>> tuple(dict(a=1, b=2).items())
(('a', 1), ('b', 2))
>>> tuple(dict(b=2, a=1).items())
(('b', 2), ('a', 1))
Of course, if you can absolutely guarantee how the dictionary has been constructed, it is possible. No rules are absolute. But in my experience, frozenset() is probably better:
>>> frozenset(dict(a=1, b=2).items())
frozenset({('b', 2), ('a', 1)})
>>> frozenset(dict(b=2, a=1).items())
frozenset({('b', 2), ('a', 1)})
(Or sometimes even id(), as, if you are confident enough that the dictionary is identical, that might be because it came from the same place. If you are building a reverse dictionary, say, or a cache of indices. Though obviously that it is much more situationally dependent.)
- Scarblac 7y agoWell. Now that dictionaries remember their order in newer Python versions, there is a case to be made that dict(a=1, b=2) is not the same dictionary as dict(b=2, a1). So they should be different dict keys, if they could be dict keys.
- Nullabillity 7y agodict(a=1,b=2) == dict(b=2,a=1) is True (on 3.7.3). I'm not too keen on introducing a third type of equality on the same type, even if it makes some theoretical sense.