假设orig是一个包含普通字符串:字符串键值对的OrderedDict,但有时该值可能是另一个嵌套的OrderedDict.
我想按键,按字母顺序(升序)对orig进行排序,并以递归方式进行.
规则:
>假设键字符串是不可预测的
>假设嵌套可以无限发生,例如级别1-50都具有字符串,OrderedDicts等作为值.
需要协助排序算法:
import string
from random import choice
orig = OrderedDict((
('a',choice(string.digits)),('b',('c',('special',OrderedDict((
('a',)))
))
sorted_copy = OrderedDict(sorted(orig.iteritems(),...))
self.assertEqual(orig,sorted_copy)
解决方法
编辑:对于python 3.6,@ pelson的答案更好
就像是:
def sortOD(od):
res = OrderedDict()
for k,v in sorted(od.items()):
if isinstance(v,dict):
res[k] = sortOD(v)
else:
res[k] = v
return res