How to sort a nested dictionary by the a nested value?

594 views Asked by At

Lets say you have this nested dictionary:

myDict = { 
          0: { 'bob': [1, 9, 4, 6, 7],
               'jack': [2, 6, 9, 8, 5, 0]}
          1: { 'dom': [1, 7, 8, 5],
               'dean': [1, 9]}
          }

How do you sort myDict[0] by the greatest of the last three values, so the output can be something like (with jack ahead of bob):

jack -> 8

bob -> 7

Thank you in advance

3

There are 3 answers

1
Mmm Donuts On

Dictionaries are accessed by key's, you can't sort them in python. You can however, EXTRACT the data and put it into a list - after which, sorting the data is rather easy!

myDict = { 
          0: { 'bob': [1, 9, 4, 6, 7],
               'jack': [2, 6, 9, 8, 5, 0]}
          1: { 'dom': [1, 7, 8, 5],
               'dean': [1, 9]}
          }

For example, you can do:

list_one = (myDict[0]['bob'][-3:])

If you want the greatest of the last three values:

greatest = list.sort(list_one)[-1] #gets the last value
0
Pynchia On

one solution is to use an orderd dictionary:

from collections import OrderedDict

def my_ordered_dict(d):
    return OrderedDict(sorted(d.items(),
                              key=lambda t: max(t[1][-3:]),
                              reverse=True))
myDict = { 
        0: my_ordered_dict({'bob': [1, 9, 4, 6, 7],
                            'jack': [2, 6, 9, 8, 5, 0]}),
        1: my_ordered_dict({'dom': [1, 7, 8, 5],
                            'dean': [1, 9]})
          }

print myDict[0]
print myDict[1]

ouputs:

OrderedDict([('jack', [2, 6, 9, 8, 5, 0]), ('bob', [1, 9, 4, 6, 7])])
OrderedDict([('dean', [1, 9]), ('dom', [1, 7, 8, 5])])

Please note in the second case dean gets ahead of dom even if its list has two elements only.

8
darthShadow On

Code :

myDict = { 
          0: { 'bob': [1, 9, 4, 6, 7],
               'jack': [2, 6, 9, 8, 5, 0]},
          1: { 'dom': [1, 7, 8, 5],
               'dean': [1, 9]}
          }
myDict[0] = sorted(myDict[0].items(),key=lambda (k,v) : max(v[-3:]),reverse=True)
print(myDict)

Output :

{0: [('jack', [2, 6, 9, 8, 5, 0]), ('bob', [1, 9, 4, 6, 7])], 1: {'dean': [1, 9], 'dom': [1, 7, 8, 5]}}

Explanation :
Convert myDict[0] to (key,value) pairs & then sort it by the max value of the last 3 elements in the value list.