Johhny Bravo
Johhny Bravo

Reputation: 199

Sorting nested dictionaries python

I am trying to solve this issue with sorting a particular nested dictionary.

Structure is as follows:

dct = {
    "test": {
        0: [1, 3],
        1: [5, 6],
    },
    "test2": {
        7: [9],
        3: [4, 6],
    }
}

I would love to be able to sort by the "test" term and the key so in the "test2" I would have first 3 and then 7.

I have tried this

arr = OrderedDict(sorted(dct.items(), key=lambda x: (x[0], x[1])))

But that doesn't seem to work. Is there any way to perform this kind of sort?

Upvotes: 0

Views: 1778

Answers (2)

Kaushik NP
Kaushik NP

Reputation: 6781

So basically since keys need to be sorted in the nested dict, go through the dictionary and transfer the data to a new dictionary.

>>> new_d = OrderedDict()

>>> for key,val in d.items():                      #go through the dictionary
        new_d[key] = OrderedDict(sorted(val.items()))       #sort according to keys

#driver values

IN : d
{
  'test' :{   0:[1,3] ,  
              1:[5,6] 
          }, 
  'test2':{ 7:[9],  
            3:[4,6]
          }
}

OUT : new_d 
OrderedDict([('test', {0: [1, 3], 1: [5, 6]}), ('test2', {3: [4, 6], 7: [9]})])

Edit : As the OP wants the dictionary's initial keys (EX : test3:{ ... } , test2:{ ... } ) to be sorted too, the below changes need to be done :

>>> initial_sort = OrderedDict(sorted(d.items()))
>>> inital_sort
OrderedDict([('test2', {7: [9], 3: [4, 6]}), ('test3', {0: [1, 3], 1: [5, 6]})])

>>> new_d = OrderedDict()

>>> for key,val in initial_sort.items():                      #go through the first key sorted dictionary 
         new_d[key] = OrderedDict(sorted(val.items())) 

#driver values

IN : d = {'test3': {0: [1, 3], 1: [5, 6]}, 'test2': {7: [9], 3: [4, 6]}}
OUT : new_d = OrderedDict([('test2', OrderedDict([(3, [4, 6]), (7, [9])])), ('test3', OrderedDict([(0, [1, 3]), (1, [5, 6])]))])

Upvotes: 2

pacholik
pacholik

Reputation: 8972

If you want outer dict and all inner dicts sorted, then you need an OrderedDict of OrderedDicts. You can create it with something like

OrderedDict(sorted((k, OrderedDict(sorted(v.items()))) for k,v in dct.items()))

Upvotes: 1

Related Questions