The Python Oracle

Dictionary in python with order I set at start

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game Looping

--

Chapters
00:00 Dictionary In Python With Order I Set At Start
00:20 Answer 1 Score 1
00:49 Accepted Answer Score 18
01:14 Answer 3 Score 20
01:24 Answer 4 Score 4
01:37 Thank you

--

Full question
https://stackoverflow.com/questions/4490...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #collections #dictionary

#avk47



ANSWER 1

Score 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')])



ACCEPTED ANSWER

Score 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.




ANSWER 3

Score 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




ANSWER 4

Score 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?