Is it possible to use collections.OrderedDict
as like normal dict syntax, with some kind of from __???__ import ???
derivative, without converting existing dicts to use [(key, value), ..., ]
? I have several embedded json's in the code and would like to keep the order.
Asked
Active
Viewed 299 times
0

xosp7tom
- 2,131
- 1
- 17
- 26
-
I would like to construct collections.OrderedDict from normal dict syntax. That is, `x={"A":1, "B":2}; assert type(x) == collections.OrderedDict`. Of course, the second is False. So, is it possible to make it happen with some kinda of hacky derivative? – xosp7tom Dec 30 '16 at 10:10
-
1Using some kind of literal syntax would not help with decoding JSON; just tell the `json.loads()` code to use `OrderedDict` when decoding. See the duplicate. – Martijn Pieters Dec 30 '16 at 10:21
1 Answers
1
It is possible to have an ordered dictionary without collections.OrderedDict
at all: just upgrade to Python 3.6.
From PEP 468, under Performance:
Note: in Python 3.6 dict is order-preserving. This virtually eliminates performance concerns.
Just use a regular dictionary.
Python 3.4.2 (v3.4.2:ab2c023a9432, Oct 6 2014, 22:16:31) [MSC v.1600 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> {1:1, 2:2}
{1: 1, 2: 2}
>>> {2:2, 1:1}
{1: 1, 2: 2}
Python 3.6.0 (v3.6.0:41df79263a11, Dec 23 2016, 08:06:12) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> {1:1, 2:2}
{1: 1, 2: 2}
>>> {2:2, 1:1}
{2: 2, 1: 1}

TigerhawkT3
- 48,464
- 6
- 60
- 97
-
-
https://docs.python.org/3.6/whatsnew/3.6.html#pep-520-preserving-class-attribute-definition-order states: 'The order-preserving aspect of this new implementation is considered an implementation detail and should not be relied upon'. – hiro protagonist Dec 30 '16 at 10:17
-
@hiroprotagonist - Odd that the PEP simply states that `dict` is now ordered, but a summary of the PEP says it's an implementation detail. – TigerhawkT3 Dec 30 '16 at 10:22
-
hmmm... what to make of that?! should the (pyton 3.6++) implementation ever go back to an unordered `dict` a lot of code would break because people did not prepare for `dict` key to be unordered... – hiro protagonist Dec 31 '16 at 08:09