-1

Consider this dictionary format, how do I sort this complex nested dictionary by The WEIGHT or HEIGHT key:

People = {
     'person1': {
          'name': 'John Cena',
          'size': {
              'height': 175,
              'weight': 100
           }
      },
      'person2': {
          'name': 'Chuck Norris',
           'size': {
               'height': 180,
               'weight': 90
           }
      },
      'person3': {
          'name': 'Jon Skeet',
          'size': {
              'height': 185,
              'weight': 110
          }
      }
}
Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251

1 Answers1

1

Dictionaries can't be sorted, but .items() returns a list of key/value pairs. Use the key parameter of sorted to indicate the field to sort on. Python 3.7 and later allow dicts to maintain insertion order, so converting the result back to a dict will be ordered:

>>> People = { 'person1': { 'name': 'John Cena', 'size': { 'height': 175, 'weight': 100 } }, 'person2': { 'name': 'Chuck Norris', 'size': { 'height': 180, 'weight': 90 } }, 'person3': { 'name': 'Jon Skeet', 'size': { 'height': 185, 'weight': 110 } } }
>>> dict(sorted(People.items(),key=lambda x: x[1]['size']['weight']))
{'person2': {'name': 'Chuck Norris', 'size': {'height': 180, 'weight': 90}}, 'person1': {'name': 'John Cena', 'size': {'height': 175, 'weight': 100}}, 'person3': {'name': 'Jon Skeet', 'size': {'height': 185, 'weight': 110}}}
Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251