我有一本字典,我想根据子字典列表中所有设备的会话总数对父字典进行排序/重新排序
编辑,我使用python 3.6
使用以下示例数据,我想订购
我如何实现这种排序,这种数据结构可能吗?
{
"London": {
"EDGE-01": [
{
"bgp_peer_as": "1",
"bgp_session": "3:35",
"bgp_routes": "0",
"service_status": "Down",
"circuit_name": "MPLS",
"subnet_name": null,
"last_updated": "2019-05-08 17:45:43",
"time_error": true,
"service_name": "MPLS"
}
]
},
"Manchester": {
"EDGE-01": [
{
"bgp_peer_as": "1",
"bgp_session": "1w1d",
"bgp_routes": "2",
"service_status": "Up",
"circuit_name": null,
"subnet_name": "Live ",
"last_updated": "2019-05-08 17:45:13",
"time_error": true,
"service_name": "Live Primary"
},
{
"bgp_peer_as": "2",
"bgp_session": "1w6d",
"bgp_routes": "140",
"service_status": "Up",
"circuit_name": null,
"subnet_name": "Dev Primary",
"last_updated": "2019-05-08 17:45:08",
"time_error": true,
"service_name": "Dev Primary"
}
],
"INT-GW-01": [
{
"bgp_peer_as": "10",
"bgp_session": "1d2h",
"bgp_routes": "10",
"service_status": "Up",
"circuit_name": null,
"subnet_name": "PUBLIC",
"last_updated": "2019-05-08 17:41:58",
"time_error": true,
"service_name": "PUBLIC"
}
]
},
"Edinburgh": {
"EDGE-01": [
{
"bgp_peer_as": "1",
"bgp_session": "3:35",
"bgp_routes": "0",
"service_status": "Down",
"circuit_name": "MPLS",
"subnet_name": null,
"last_updated": "2019-05-08 17:45:43",
"time_error": true,
"service_name": "MPLS"
},
{
"bgp_peer_as": "65001",
"bgp_session": "1w6d",
"bgp_routes": "140",
"service_status": "Up",
"circuit_name": null,
"subnet_name": "SV Primary",
"last_updated": "2019-05-08 17:45:08",
"time_error": true,
"service_name": "SV Primary"
}
]
}
}
答案 0 :(得分:2)
按照@masasa的建议,您可以在集合模块中使用 for(const [j, k, l, m] of loop(1, 2, 3, 4)) {
//...
}
:
OrderedDict
对于python3.7,您可以只使用标准的from collections import OrderedDict
# You can use sorted to get the keys of the dict based on the len of all devices
# and reverse=True will order from longest to shortest
sorted_keys = sorted([(k, sum(len(dev) for name, dev in v.items())) for k,v in y.items()], key=lambda x: x[1], reverse=True)
# [('Manchester', 3), ('Edinburgh', 2), ('London', 1)]
# So to put this into OrderedDict
z = OrderedDict((k, y[k]) for k, _ in sorted_keys)
z.keys()
odict_keys(['Manchester', 'Edinburgh', 'London'])
,因为@buran已经回答了,其他人已经发表了评论
答案 1 :(得分:0)
import json
spam = json.loads("""{
...
}""")
eggs = dict(sorted(spam.items(), key=lambda item: sum(len(value2) for value2 in item[1].values()), reverse=True))
print(eggs)
请注意,您所拥有的不是有效的字典(例如,null
,true
之类的值),显然是json。
我的解决方案假定使用python3.7 +命令。如果不是这种情况,那么鸡蛋应该是collections.OrderedDict
的实例。