我有一本字典,看起来像这样
{
'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'
该值是一个dict,其中包含收到的请求和每页的点击数。.问题是如何'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+,在字典键的顺序被保留,并给予你的字典存储在变量d
,你可以在的项目进行排序d['Host-A']['requests']
的子字典用钥匙的函数,返回hit_count
的子字典的价值给定元组的第二个项目,然后将结果排序后的项目序列传递给dict
构造函数以构建新的排序后的dict:
d['Host-A']['requests'] = dict(sorted(d['Host-A']['requests'].items(), key=lambda t: t[1]['hit_count'], reverse=True))
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句