A
A
Alexey Yarkov2015-11-17 20:25:50
Python
Alexey Yarkov, 2015-11-17 20:25:50

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())

Now a dictionary is stored in self.__JSON, but the elements in it are sorted by key, but I don’t need it)) In principle, this does not affect the operation of the program, but I want to save the formatting and order of the keys when writing. Using json.load () read - the same garbage.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
sim3x, 2015-11-17
@yarkov

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

N
newpy, 2015-11-18
@newpy

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"

It became:
"APP": {
        "description": "Application description", 
        "name": "Application name", 
        "version": "1.0.0"

As sim3x already answered and gave links, I just give an example from there, in which particular place it is written how to do it.
>>> # 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 question

Ask a Question

731 491 924 answers to any question