Dictionary in python with order I set at start
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Horror Game Menu Looping
--
Chapters
00:00 Question
00:31 Accepted answer (Score 18)
01:01 Answer 2 (Score 20)
01:14 Answer 3 (Score 4)
01:36 Answer 4 (Score 1)
02:09 Thank you
--
Full question
https://stackoverflow.com/questions/4490...
Answer 2 links:
https://www.python.org/dev/peps/pep-0468/
Answer 3 links:
[recipe]: http://code.activestate.com/recipes/1077.../
[What is the best ordered dict implementation in python?]: https://stackoverflow.com/q/719744/64633
--
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?