如何按嵌套键对嵌套字典进行排序

How to sort a nested dictionary by a nested key

我真的找不到我要找的问题,也不理解已经存在的问题。 我有一个像这样的二维字典:

 {'alim2': {'running': 1470.0, 'swimming': 650.0, 'total': 2120.0, 'cycling': 0}, 'brownv4': {'running': 0, 'swimming': 0, 'total': 0, 'cycling': 0},
'mahroosm5': {'running': 1180.0, 'swimming': 590, 'total': 6647.0, 'cycling': 4877.0},
'turnerb3': {'running': 1180.0, 'swimming': 500, 'total': 1680.0, 'cycling': 0}}

这些数字基本上是每项运动消耗的卡路里,我需要让程序按照 'total' 值的升序对键(用户名 'brownv4')进行排序。 如果输出只是字典的键,在本例中是用户名,那也会非常方便。 所以他的输出会是这样的: mahroosm5、alim2、turnerb3、brownv4

这不是真正的排序,因为字典是无序的,但您可以尝试使用 sorted()key 一篇不错的文章 here, If you really need a dict you can put the sorted() return value inside an Ordered Dict

import pprint

my_dict = {'alim2': {'running': 1470.0, 'swimming': 650.0, 'total': 2120.0, 'cycling': 0}, 'brownv4': {'running': 0, 'swimming': 0, 'total': 0, 'cycling': 0},
'mahroosm5': {'running': 1180.0, 'swimming': 590, 'total': 6647.0, 'cycling': 4877.0},
'turnerb3': {'running': 1180.0, 'swimming': 500, 'total': 1680.0, 'cycling': 0}}

pprint.pprint(sorted(my_dict.items(), key=lambda key_:key_[1]['total'])) 

输出:

[('brownv4', {'cycling': 0, 'running': 0, 'swimming': 0, 'total': 0}),
 ('turnerb3',
  {'cycling': 0, 'running': 1180.0, 'swimming': 500, 'total': 1680.0}),
 ('alim2',
  {'cycling': 0, 'running': 1470.0, 'swimming': 650.0, 'total': 2120.0}),
 ('mahroosm5',
  {'cycling': 4877.0, 'running': 1180.0, 'swimming': 590, 'total': 6647.0})]  

此外,如果您希望它反转,您可以添加 reverse=True 参数。