这个问题在这里已经有了答案:
sort dict by value python [duplicate]
(9 个回答)
2年前关闭。
我有一本字典,看起来像这样
{
'Host-A': {'requests':
{'GET /index.php/dashboard HTTP/1.0': {'code': '200', 'hit_count': 3},
'GET /index.php/cronjob HTTP/1.0': {'code': '200', 'hit_count': 4},
'GET /index.php/setup HTTP/1.0': {'code': '200', 'hit_count': 2}},
'total_hit_count': 9},
}
如您所见
'Host-A'
该值是一个字典,包含收到的请求和每页上的点击次数.. 问题是如何对 'requests'
进行排序按降序排列。这样我就可以获得最高的请求。正确解决方案输出的示例如下:
{
'Host-A': {'requests':
{'GET /index.php/cronjob HTTP/1.0': {'code': '200', 'hit_count': 4},
'GET /index.php/dashboard HTTP/1.0': {'code': '200', 'hit_count': 3},
'GET /index.php/setup HTTP/1.0': {'code': '200', 'hit_count': 2}},
'total_hit_count': 9},
}
我感谢您的帮助
最佳答案
假设您使用的是 Python 3.7+,其中保留了 dict 键的顺序,并将您的 dict 存储在变量 d
中。 ,您可以对 d['Host-A']['requests']
的项目进行排序带有返回 hit_count
的键函数的 sub-dict给定元组的第二项中子字典的值,然后将结果排序的项序列传递给 dict
构造新的排序字典:
d['Host-A']['requests'] = dict(sorted(d['Host-A']['requests'].items(), key=lambda t: t[1]['hit_count'], reverse=True))
关于Python 按值降序对嵌套字典进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55764880/