[Python-ideas] Proposal: New syntax for OrderedDict, maybe built-in

Erik Bray erik.m.bray at gmail.com
Wed Sep 10 23:25:51 CEST 2014


On Thu, Sep 4, 2014 at 2:00 PM, David Wilson <dw+python-ideas at hmmz.org> wrote:
> On Thu, Sep 04, 2014 at 07:35:06PM +0200, Norman Hooper wrote:
>
>> I work with OrderedDict a lot, because JSON represents an OrderedDict
>> and I need to work with JSON a lot.
>>
>> With the ubiquity of JSON, it may also be time to promote OrderedDict
>> to a built-in type too.
>
> Neither JSON objects nor JavaScript object properties preserve
> enumeration order. This is a common misconception since implementations
> tend to preserve order when the number of keys is small, since they may
> use a more efficient internal representation in that case, whose
> enumeration order depends on order the properties were defined in.

JSON/JavaScript might not be the best use case for this reason.  But YAML is!

YAML has an "omap" construct [1] for representing ordered mappings.
In "block style" this is represented like:

- aardvark: African pig-like ant eater. Ugly.
- anteater: South-American ant eater. Two species.
- anaconda: South-American constrictor snake. Scaly.

This syntax is basically the same as that for a list of one-element mappings.

In YAML's "flow style" this equates to exactly the OP's proposal:

["aardvark": "...", "anteater": "...", "anaconda": "..."]


Unfortunately there's no way for the YAML parser to disambiguate this
from a list of one-element mappings, unless the "!!omap" tag is
explicitly prepended.  But in some of my own applications I find it
useful enough to just assume this should be an OrderedDict.  Though
it's just as easy only make an OrderedDict when "!!omap" is used.

In PyYAML this is supported by returning a list of tuples, though it's
easy to then wrap that in an OrderedDict:

>>> yaml.load("['a': 1, 'b': 2]")
[{'a': 1}, {'b': 2}]
>>> yaml.load("!!omap ['a': 1, 'b': 2]")
[('a', 1), ('b', 2)]

I have one application that uses this extensively and would personally
like to see it in Python. But I think the objections thus far are
(mostly) reasonable.

Erik


[1] http://yaml.org/type/omap.html


More information about the Python-ideas mailing list