The accepted answer of this post clearly mentions that it's not possible to sort a dictionary in Python. However, the next answer claims that it is actually possible to do a "sort by dictionary values". My situation is close to this post. Here, the main dictionary is suggested to sort by a value of a key of one of the inner dictionaries using OrderedDict
. In my case, I want the key of the main dictionary be intact but the values (which are dictionaries itself) to be sorted in descending order. I have the following dictionary:
dict = {
1: {1: -8, 2: -5, 3: -6, 4: -2},
2: {1: -7, 2: -6, 3: -5, 4: -1},
3: {1: -7, 2: -6, 3: -4, 4: -5},
4: {1: -7, 2: -4, 3: -6, 4: -8}
}
How can I arrange the inner dictionaries such that the resulting dictionary becomes as follows:
dict = {
1: {4: -2, 2: -5, 3: -6, 1: -8},
2: {4: -1, 3: -5, 2: -6, 1: -7},
3: {3: -4, 4: -5, 2: -6, 1: -7},
4: {2: -4, 3: -6, 1: -7, 4: -8}
}
The installed python in my system is Python 3.6.5. It has become just a week since I ran my first python code. Hence, I'm very new to python. I had asked few questions before, which didn't receive a good response. I had to delete a question too. I'm in danger of being blocked for asking any more questions. I saw many posts regarding the sorting of a dictionary in python and the mixed answers has confused me. Basically, I am asking to sort the keys of the inner dictionary by their values (without changing the main dictionary's key order). Is it even possible? How can I do it? Please help me!