Man*_*nix 5 python sorting dictionary python-3.x
我有一本字典,看起来像这样
{
'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},
}
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,'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},
}
Run Code Online (Sandbox Code Playgroud)
我感谢您的帮助
假设您使用的是Python 3.7+,其中保留了字典键的顺序,并且给定存储在变量中的字典d
,您可以d['Host-A']['requests']
使用返回子字典值的键函数hit_count
对子字典的项目进行排序给定元组的第二项,然后将生成的排序项序列传递给dict
构造函数以构建新的排序字典:
d['Host-A']['requests'] = dict(sorted(d['Host-A']['requests'].items(), key=lambda t: t[1]['hit_count'], reverse=True))
Run Code Online (Sandbox Code Playgroud)