1

I am trying to use OrderedDict in Python where I am ordering the dictionary data using lambda. Somehow I am not able write this correctly. With reference to this post

sorting a nested dictionary with lists in python

I tried to order my dictionary using two keys 1. First group (Info, Code, Process etc) 2. As second tuple value of inner dictionary (7, 2, 45, 18, 19 etc). However, not getting what I want. Here is my input -

   a = {'Info': {3: ('info1', 7), 4: ('info4', 2)},
         'Process': {1: ('info2', 45), 8: ('info8', 18), 10: ('info11', 19)},
         'Code': {23: ('info3', 45), 27: ('info21', 34)}}

print sorted(a.items(), key=lambda x: (x[1].values()[0][1], x[0]))

Ultimately, I want to get this information in an OrderedDict and iterate over it in a particular order.

Can anyone help?

Thanks for the response folks! Just adding the expected output. See, first it's ordered by the main key (Code, Info, Process) and then the inner dictionary is ordered by second element in the value tuple (34, 45), (2,7), (18, 19, 45)

a = {'Code': {27: ('info21', 34), 23: ('info3', 45)},
     'Info': {4: ('info4', 2), 3: ('info1', 7)},
     'Process': {8: ('info8', 18), 10: ('info11', 19), 1: ('info2', 45)},
    }

I am OK if we skip the first key ordering i.e. only the inner dictionary is ordered by second element in the value tuple (34, 45), (2,7), (18, 19, 45). So the expected answer in this case would be:

a = {'Info': {4: ('info4', 2), 3: ('info1', 7)},
     'Process': {8: ('info8', 18), 10: ('info11', 19), 1: ('info2', 45)},
     'Code': {27: ('info21', 34), 23: ('info3', 45)},
    }

I hope this explains my problem. Again thanks for responding so quick.

4

0 に答える 0