Olga
Olga

Reputation: 1455

how to order dictionary python (sorting)

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?

Upvotes: 3

Views: 14445

Answers (2)

Dmitry Zagorulkin
Dmitry Zagorulkin

Reputation: 8548

you should use OrderedDict instead of Dict.

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

Upvotes: 3

falsetru
falsetru

Reputation: 369074

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': {}}

Upvotes: 17

Related Questions