简体   繁体   中英

Sort a complex nested dictionary

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

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

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