Python 按值降序对嵌套字典进行排序

标签 python python-3.x sorting dictionary

这个问题在这里已经有了答案:





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/

相关文章:

python - 多重图的线图

python-3.x - 看起来像对象的整数数组

python - 我请求的页面不代表与BeautifulSoup4相同的结构

python - 获取组的 n 个最大值

python - 如何使用 h5py 更新二维数组?

python - 在 Twisted 和 Django 之间共享数据库

PHP修复数组中的数字键

javascript - 根据字符串对对象数组进行排序

python - 我如何编写 if 条件以在 Python 中跳出 for 循环

python-3.x - 如何以编程方式展开/折叠和选择树中的项目?