Monday 2 August 2021

Sort a Python dictionary within a dictionary

I am trying to sort a dictionary within a dictionary. My goal is to sort the 'sub' dictionary ['extra'] based on it's values, from high to low.The problem I'm having is that my 'sub' dictionary is nested deep within the main dictionary. Using other examples, I can do this for one level higher, see my code below. So instead of sorting 'marks', I would like to sort the items 1,2 & 3 based on their values. Code:

# initializing dictionary
test_dict = {'Nikhil' : { 'roll' : 24, 'marks' : 17, 'extra' : {'item1': 2, 'item2': 3, 'item3': 5}},
             'Akshat' : {'roll' : 54, 'marks' : 12, 'extra' : {'item1': 8, 'item2': 3, 'item3': 4}}, 
             'Akash' : { 'roll' : 12, 'marks' : 15, 'extra' : {'item1': 9, 'item2': 3, 'item3': 1}}}
  
# printing original dict
print("The original dictionary : " + str(test_dict))
  
# using sorted()
# Sort nested dictionary by key
res = sorted(test_dict.items(), key = lambda x: x[1]['marks'])

# print result
print("The sorted dictionary by marks is : " + str(res))

# How to sort on 'extra'? 

So this is what I want it to look like:

sorted_dict = {'Nikhil' : { 'roll' : 24, 'marks' : 17, 'extra' : {'item3': 5, 'item2': 3, 'item1': 2}},
             'Akshat' : {'roll' : 54, 'marks' : 12, 'extra' : {'item1': 8, 'item3': 4, 'item2': 3}}, 
             'Akash' : { 'roll' : 12, 'marks' : 15, 'extra' : {'item1': 9, 'item2': 3, 'item3': 1}}}


from Sort a Python dictionary within a dictionary

No comments:

Post a Comment