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

Question:

How can 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?

Answers:

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}}
Answered By: ouroboros1
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.