Answer the question
In order to leave comments, you need to log in
How to get an unsorted dictionary?
There is a json file. Formatted beautifully, indented, the keys are in the right order. I read from it like this:
with codecs.open(self.__configPath, "r", encoding = self.__charset) as f:
self.__JSON = eval(f.read())
Answer the question
In order to leave comments, you need to log in
Dict in python is not sorted by key
Use OrderedDict
https://docs.python.org/3/library/collections.html
https://docs.python.org/2/library/collections.html
dictionary is an unordered set of key: value pairs
which in translation means that dictionaries in python do not guarantee order preservation (for example, unlike PHP). So it is unlikely that you have a dictionary sorted by key. By the way, pay attention to how you were, and how it became. Just the order of the elements has changed BEFORE and AFTER.
It was:
"APP": {
"name": "Application name",
"description": "Application description",
"version": "1.0.0"
"APP": {
"description": "Application description",
"name": "Application name",
"version": "1.0.0"
>>> # regular unsorted dictionary
>>> d = {'banana': 3, 'apple':4, 'pear': 1, 'orange': 2}
>>> # dictionary sorted by key
>>> OrderedDict(sorted(d.items(), key=lambda t: t[0]))
OrderedDict([('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)])
>>> # dictionary sorted by value
>>> OrderedDict(sorted(d.items(), key=lambda t: t[1]))
OrderedDict([('pear', 1), ('orange', 2), ('banana', 3), ('apple', 4)])
>>> # dictionary sorted by length of the key string
>>> OrderedDict(sorted(d.items(), key=lambda t: len(t[0])))
OrderedDict([('pear', 1), ('apple', 4), ('orange', 2), ('banana', 3)])
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question