【问题标题】:Python sort nested dictionaries by value descending [duplicate]Python按值降序对嵌套字典进行排序[重复]
【发布时间】:2019-09-09 21:41:36
【问题描述】:

我有一本像这样的字典

{
'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 python-3.x sorting dictionary


【解决方案1】:

假设您使用的是 Python 3.7+,其中保留了 dict 键的顺序,并且将您的 dict 存储在变量 d 中,您可以使用以下键函数对 d['Host-A']['requests'] 子dict 的项目进行排序返回给定元组的第二项中子字典的hit_count 值,然后将生成的排序项序列传递给dict 构造函数以构建新的排序字典:

d['Host-A']['requests'] = dict(sorted(d['Host-A']['requests'].items(), key=lambda t: t[1]['hit_count'], reverse=True))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-01
    • 1970-01-01
    • 2021-03-08
    • 2020-11-11
    • 1970-01-01
    • 1970-01-01
    • 2022-01-19
    相关资源
    最近更新 更多