3

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?

Olga
  • 1,395
  • 2
  • 25
  • 34

2 Answers2

17

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': {}}
falsetru
  • 357,413
  • 63
  • 732
  • 636
3

you should use OrderedDict instead of Dict.

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

Dmitry Zagorulkin
  • 8,370
  • 4
  • 37
  • 60