0

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?

4
  • Wait, how is test2 related to test here? Commented Oct 18, 2017 at 14:22
  • @KaushikNP Basically there is a dictionary, which has keys "test" and "test2". Each of these keys holds as a value that inner dictionary. So for instance dict["test"] = {0: [1,3], 1:[5,6]} Commented Oct 18, 2017 at 14:38
  • Basically, sort according to key in your dictionary right? Commented Oct 18, 2017 at 14:44
  • @Kaushik NP basically sort by key and then sort by key again Commented Oct 18, 2017 at 15:03

2 Answers 2

2

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])]))])
Sign up to request clarification or add additional context in comments.

1 Comment

Yeah, I am using python 2.7
1

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()))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.