Python 3: Plist as OrderedDict

Ben Finney ben+python at benfinney.id.au
Mon Feb 8 23:17:23 EST 2010


Gnarlodious <gnarlodious at gmail.com> writes:

> from plistlib import readPlist
> dict=readPlist('/path/file.plist')
> --> arbitrarily ordered dictionary compared to the XML file

Right. The items in a dict are unordered, and when serialised to a list
they will appear in an arbitrary, unpredictable order.

    >>> foo = dict(
    ...     [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)])
    >>> foo
    {'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4}

> from collections import OrderedDict
> OrderedDict(readPlist('/path/file.plist'))
> --> essentially does the same thing as the previous

Yes, because you are initialising an OrderedDict instance from a dict.
That accesses the dict items as an iterable, which of course is going to
retrieve the items in an arbitrary, unpredictable order.

    >>> foo.items()
    dict_items([('a', 1), ('c', 3), ('b', 2), ('e', 5), ('d', 4)])

The OrderedDict then faithfully remembers the arbitrary ordering of the
items.

    >>> from collections import OrderedDict
    >>> OrderedDict(foo.items())
    OrderedDict([('a', 1), ('c', 3), ('b', 2), ('e', 5), ('d', 4)])

> readPlist seems to do the scrambling

Nothing “does” the scrambling; the order is forgotten by the dict as
soon as the items go in.

> I "upgraded" to Py3 to have OrderedDict, so please don't say it is
> impossible...

What you'll need to do is insert the items into the OrderedDict instance
in the desired order. You will, of course, need to define what that
desired order is.

    >>> sorted(foo.items(), key=(lambda item: item[0]))
    [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)]
    >>> OrderedDict(sorted(foo.items(), key=(lambda item: item[0])))
    OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)])

-- 
 \          “When we talk to God, we're praying. When God talks to us, |
  `\         we're schizophrenic.” —Jane Wagner, via Lily Tomlin, 1985 |
_o__)                                                                  |
Ben Finney



More information about the Python-list mailing list