我遇到了完全相同的问题,并设计了一个轻量级的通用解决方案:
from collections import OrderedDict
def make_custom_sort(orders):
orders = [{k: -i for (i, k) in enumerate(reversed(order), 1)} for order in orders]
def process(stuff):
if isinstance(stuff, dict):
l = [(k, process(v)) for (k, v) in stuff.items()]
keys = set(stuff)
for order in orders:
if keys.issuperset(order):
return OrderedDict(sorted(l, key=lambda x: order.get(x[0], 0)))
return OrderedDict(sorted(l))
if isinstance(stuff, list):
return [process(x) for x in stuff]
return stuff
return process
首先,您创建一个自定义顺序排序函数的实例:
custom_sort = make_custom_sort([ ["Admin", "Groups", "Network", "Subnets", "Entries"] ])
现在,实际排序:
result = custom_sort(my_dataset)
丢失的键最终以未指定的顺序被拒绝。请注意,此闭包是递归的。如双括号所示,您可以指定嵌套在结构中的各种字典所需的排序顺序。
GitHub上的项目:https ://github.com/laowantong/customsort