-2

How do I sort the values in a nested dictionary and result should also be in dict format??

For eg:

   { 1: {2: 3.4 ,3: 4.5, 4:1.2},
     2: {3: 35.6 ,4: 6.7, 5:2},
     3: {4:45, 6:75}
    }

How do I sort the values in this nested dict to get the results(reverse sort) like: { 1: {3:4.5, 2:3.4, 4:1.2}, 2: {3: 35.6 ,4: 6.7, 5:2}, 3: {6:75, 4:45} }

new_learner
  • 51
  • 1
  • 6

2 Answers2

0

What you are wanting is actually not possible.

When a dict is written, and then read later, the read order does not have to match the write order.

This can be demonstrated directly in the python command interpreter:

Here we will write into d the answer specified above...

>>> d = { 1: {3:4.5, 2:3.4, 4:1.2}, 2: {3: 35.6 ,4: 6.7, 5:2}, 3: {6:75, 4:45} }

But if we ask for it back, we get something different.... thats just how type dict works.

>>> d
{1: {2: 3.4, 3: 4.5, 4: 1.2}, 2: {3: 35.6, 4: 6.7, 5: 2}, 3: {4: 45, 6: 75}}

Lesson: If you want a data structure that is sortable or remembers a sort order, use an array or a list, or as @JesseMu suggested, an OrderedDict

Here I'll show how to solve the sorting problem with arrays.

Instead, suppose your input data was an array of arrays of pairs, like this:

d = [ [(2, 3.4),  (3, 4.5), (4, 1.2)],\
      [(3, 35.6), (4, 6.7), (5, 2)],\
      [(4, 45), (6,75) ]\
    ]

Then what you need to do is reverse sort each array by the value of the 2nd field (which is field 1 because the first field is field 0), and that looks like this:

d_sorted = [sorted(a, key=lambda p: -p[1]) for a in d]

d_sorted
[[(3, 4.5), (2, 3.4), (4, 1.2)], [(3, 35.6), (4, 6.7), (5, 2)], [(6, 75), (4, 45)]]
Paul
  • 26,170
  • 12
  • 85
  • 119
0

use OrderedDict

Example:

from collections import OrderedDict

d = OrderedDict()
James the Great
  • 941
  • 2
  • 14
  • 46