简体   繁体   中英

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

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?

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}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM