13

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?

Aphex
  • 7,390
  • 5
  • 33
  • 54
user278618
  • 19,306
  • 42
  • 126
  • 196

4 Answers4

20
from collections import OrderedDict

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

print(d)

OrderedDict([('server', 'mpilgrim'), ('database', 'master'), ('mynewkey', 'mynewvalue')])
Aphex
  • 7,390
  • 5
  • 33
  • 54
  • No, it's not ok, because, at start "server":"mpilgrim" was first. Now is second – user278618 Dec 20 '10 at 15:19
  • Right, I fixed the key insertion once I noticed. For `OrderedDicts`, you need to add keys using the [ ] operator (`__setitem__`). Insertion order is preserved. – Aphex Dec 20 '10 at 15:21
18

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.

  • The easiest implementation being a list of tuples, especiall if speed isn't an issue. – Katriel Dec 20 '10 at 16:04
  • Yes, that's easiest, but it performs *horribly*. Especially when it's used with algorithms that assume "real" (i.e. `O(1)` read/write/`in`) dicts –  Dec 20 '10 at 16:20
4

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

andy boot
  • 11,355
  • 3
  • 53
  • 66
1

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?

Community
  • 1
  • 1
Rod
  • 52,748
  • 3
  • 38
  • 55