how to order dictionary python (sorting)

14,070

Solution 1

http://docs.python.org/2/library/collections.html#collections.OrderedDict

An OrderedDict is a dict that remembers the order that keys were first inserted. If a new entry overwrites an existing entry, the original insertion position is left unchanged. Deleting an entry and reinserting it will move it to the end.

>>> import collections
>>> a = collections.OrderedDict()
>>> a['w'] = {}
>>> a['a'] = {}
>>> a['s'] = {}
>>> a
OrderedDict([('w', {}), ('a', {}), ('s', {})])
>>> dict(a)
{'a': {}, 's': {}, 'w': {}}

Solution 2

you should use OrderedDict instead of Dict.

http://docs.python.org/2/library/collections.html

Share:
14,070
Olga
Author by

Olga

Updated on June 08, 2022

Comments

  • Olga
    Olga almost 2 years

    I use Python dictionary:

    >>> a = {}
    >>> a["w"] = {}
    >>> a["a"] = {}
    >>> a["s"] = {}
    >>> a
    {'a': {}, 's': {}, 'w': {}}
    

    I need:

    >>> a
    {'w': {}, 'a': {}, 's': {}}
    

    How can I get the order in which I filled the dictionary?