-2

How can I sort this nested dictionary by the inner values. The keys will change so cannot sort by keys. The keys are integers and the values are floats.

NestedDict = {'1': {2: 0.3, 7: 0.5, 4: 0.4, 3: 0.75},
              '2': {5: 0.3, 7: 0.5, 4: 0.4, 1: 0.75},
              '3': {15: 0.3, 7: 0.5, 4: 0.4, 70: 0.75}}

This is the result I need. The values are sorted from greatest to least regardless of the keys.

# NestedDict = {'1': {3: 0.75, 7: 0.5, 4: 0.4, 2: 0.3},
#               '2': {1: 0.75, 7: 0.5, 4: 0.4, 5: 0.3},
#               '3': {70: 0.75, 7: 0.5, 4: 0.4, 15: 0.3}}
HelloWorld123
  • 79
  • 2
  • 9

2 Answers2

3

You can use a dictionary comprehension to rebuild the dictionaries in an ordered way. From Python 3.7 onward the order in which you add items to a dictionary is preserved.

NestedDict = {
    outer_key: {
        inner_key: inner_value for inner_key, inner_value in
        sorted(inner_dict.items(), key=lambda d: -d[1])
    }
    for outer_key, inner_dict in NestedDict.items()
} 

Now NestedDict is

{'1': {3: 0.75, 7: 0.5, 4: 0.4, 2: 0.3},
 '2': {1: 0.75, 7: 0.5, 4: 0.4, 5: 0.3},
 '3': {70: 0.75, 7: 0.5, 4: 0.4, 15: 0.3}}

Outer level is the same but for inner level we are iterating over a sorted version of the inner dictionary (sorted by their values, given by d[1] where the minus sign indicates a decreasing order).

ayhan
  • 70,170
  • 20
  • 182
  • 203
  • Thank you. But I am afraid I don't know how to implment the above as I just tried. Would you mind writing it mentioned assingment in full? – HelloWorld123 Oct 11 '19 at 19:58
  • @HelloWorld123 Oh I just meant `NestedDict = {outer_key: ... ` I've updated the answer. Let me know if it's clearer. – ayhan Oct 11 '19 at 20:01
0

An alternative to dictionary comprehensions. Not necessarily better, different. This is predicated on Python 3.6 or greater, which maintains insertion order, else one must use an OrderedDict. Dictionary comprehensions do not give you that option.

NestedDict = {'1': {2: 0.3, 7: 0.5, 4: 0.4, 3: 0.75},
              '2': {5: 0.3, 7: 0.5, 4: 0.4, 1: 0.75},
              '3': {15: 0.3, 7: 0.5, 4: 0.4, 70: 0.75}}

keys = [k for k in NestedDict.keys()]
dict_values = [v for v in NestedDict.values()]
dict_values = [dict(sorted(x.items(), key=lambda kv: -kv[1])) for x in dict_values] # or OrderedDict

NestedDict = dict(zip(keys, dict_values)) # or OrderedDict
print(NestedDict)

Prints:

{'1': {3: 0.75, 7: 0.5, 4: 0.4, 2: 0.3}, '2': {1: 0.75, 7: 0.5, 4: 0.4, 5: 0.3}, '3': {70: 0.75, 7: 0.5, 4: 0.4, 15: 0.3}}
Booboo
  • 38,656
  • 3
  • 37
  • 60