12
votes

I'm making dictionary:

d = {"server":"mpilgrim", "database":"master"}
d['mynewkey'] = 'mynewvalue'

But when I display it I saw that this dict is reversed.

print(d)

{'mynewkey': 'mynewvalue', 'database': 'master', 'server': 'mpilgrim'}

How to reverse it back?

Or if it is true that dictionary is not sortable what I must to use to have collection where the order of that informations matters?

4

4 Answers

20
votes
from collections import OrderedDict

d = OrderedDict()
d["server"] = "mpilgrim"
d["database"] = "master"
d['mynewkey'] = 'mynewvalue'

print(d)

OrderedDict([('server', 'mpilgrim'), ('database', 'master'), ('mynewkey', 'mynewvalue')])
18
votes

Dictionary are unordered (the order is deterministic, but depends on a handful of factors you don't even think of and shouldn't care about - hash of the keys, order of insertion, collisions, etc). In Python 2.7+, use collections.OrderedDict. If you must use an older version, there are various implementations google can point you to.

4
votes

If you are using python 3.6 dictionaries are now ordered by insertion order

https://www.python.org/dev/peps/pep-0468/

Otherwise (as other people have said) I would recommend collections.OrderedDict

1
votes

Your dictionnary is not quite reverted. It is sorted partly according to the hash of you keys. You can't change this order (not without using a custom dictionary). In python 2.7 or later you can use an ordered dictionary (collections.OrderedDict).

In earlier version you can use the following recipe.

Also have a look at this question : What is the best ordered dict implementation in python?