[英]Sort a complex nested dictionary
Consider this dictionary format, how do I sort this complex nested dictionary by The WEIGHT or HEIGHT key:考虑这种字典格式,我如何按 WEIGHT 或 HEIGHT 键对这个复杂的嵌套字典进行排序:
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.字典无法排序,但.items()
返回键/值对列表。 Use the key
parameter of sorted
to indicate the field to sort on.使用sorted
的key
参数来指示要排序的字段。 Python 3.7 and later allow dicts to maintain insertion order, so converting the result back to a dict will be ordered: Python 3.7 及更高版本允许字典维护插入顺序,因此将结果转换回字典将被排序:
>>> 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}}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.