6 ms·
I still see dict ordering as an implementation detail; not a technical one but a descriptive one. If you want to rely on insertion order, use collections.Ordere
by rcfox 7y ago
I still see dict ordering as an implementation detail; not a technical one but a descriptive one. If you want to rely on insertion order, use collections.OrderedDict. It communicates your intention far better, and there should be no overhead.
- xapata 7y agoOrderedDict is less efficient. It's best to replace usage with basic dict where possible to improve efficiency. There is one obscure feature of OrderedDict that isn't in the basic, so it can't always be swapped.
- rcfox 7y agoReally? I would have figured they'd just do something like: class OrderedDict(dict): pass (Plus a little bit of API shimming.)
- zurtex 7y agoNo, OrderedDict has it's own C implementation which was created just before it was decided that dict would preserve order across iteration. Further there is a big difference, regular dict preserves order across iteration but OrderedDict treats order up to equality. I.e. this returns True: {1: 1, 2: 2} == {2: 2, 1: 1} Where as this returns False: OrderedDict({1: 1, 2: 2}) == OrderedDict({2: 2, 1: 1}) To make that difference speedy it needs to be done on the C level.
- masklinn 7y agoAlso ordereddicts provide methods to move items to the start or end, and remove items specifically at the start or end, not so for regular dicts.
- xapata 7y agodict has popitem for removing at the end. That used to be arbitrary, but now it (de facto) means last-inserted.
- ehsankia 7y agoFor the former, I realize that's how it's done now, but there's nothing forcing it to stay that way. For the latter issue, as explained above, can't they just implement a replacement __eq__ only for OrderedDict, and still re-use the new dict implementation? Similarly, any subtle difference can be shimmed on top of the new implementation inside Python, no?
- xapata 7y agoDepends what OrderedDict was being used for. If used for some of the obscure ordering features, replacement with dict + a shim might be a slowdown.
- xapata 7y agoThe builtins have some optimizations from the compiler and interpreter that Python-defined classes don't benefit from. The dict type especially so, because it's used to implement so many things.
- fctorial 7y agoOrdetedDict = dict