1

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?

ouroboros1
  • 9,113
  • 3
  • 7
  • 26
  • Could you elaborate how the output is considered as sorted? Is it the sum? – amew646 Jul 28 '22 at 08:00
  • @amew646 "It is now sorted by the value of keys VALUE1" – matszwecja Jul 28 '22 at 08:01
  • It's sorted using the value of the keys `VALUE1`. If you compare it altogether, you can see that it is sorted with the sorted result as 15, 10, 5 instead of the original 10, 5, 15 – InsrtRandomUserHere Jul 28 '22 at 08:03
  • 1
    It's not really a good idea to rely on ordering of a dictionary in a case like this. (Yes, dictionaries are sorted since 3.7 - that does not mean it's a data structure designed to be treated as sorted). – matszwecja Jul 28 '22 at 08:04
  • Does this answer your question: https://stackoverflow.com/questions/613183/how-do-i-sort-a-dictionary-by-value? – Dani Mesejo Jul 28 '22 at 08:05
  • This could be useful: https://stackoverflow.com/questions/4110665/sort-nested-dictionary-by-value-and-remainder-by-another-value-in-python – Dani Mesejo Jul 28 '22 at 08:06

1 Answers1

5

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}}
ouroboros1
  • 9,113
  • 3
  • 7
  • 26