Home > OS >  How do you sort a dictionary by a key's dictionary's value?
How do you sort a dictionary by a key's dictionary's value?

Time:07-28

How would I sort a dictionary using the values of a key's dictionary?

Input:

myDict = {
  "1":{
    "VALUE1": 10,
    "VALUE2": 5,
    "VALUE3": 3
  },
  
  "2":{
    "VALUE1": 5,
    "VALUE2": 3,
    "VALUE3": 1
  },
  
  "3":{
    "VALUE1": 15,
    "VALUE2": 2,
    "VALUE3": 4
  }

Expected output:

myDict = {
  "3": {
    "VALUE1": 15,
    "VALUE2": 2,
    "VALUE3": 4
  },
  
  "1": {
    "VALUE1": 10,
    "VALUE2": 5,
    "VALUE3": 3
  },

  "2": {
    "VALUE1": 5,
    "VALUE2": 3,
    "VALUE3": 1
  },
}

It is now sorted by the value of keys VALUE1
How would I get the expected output?

CodePudding user response:

Try:

newDict = dict(sorted(myDict.items(), key = lambda x: x[1]['VALUE1'], reverse=True))

newDict

{'3': {'VALUE1': 15, 'VALUE2': 2, 'VALUE3': 4},
 '1': {'VALUE1': 10, 'VALUE2': 5, 'VALUE3': 3},
 '2': {'VALUE1': 5, 'VALUE2': 3, 'VALUE3': 1}}
  • Related