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

5

我有一个类似这样的字典

{
'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字典是键值对,不以任何方式排序。如果需要,可以使用OrderedDict:https://docs.python.org/3/library/collections.html#ordereddict-objects - aikikode
@Gassa 我已经修改了问题。 - Manix
1个回答

4
假设您正在使用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))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接