我认为而不是 OrderedDict,使用 defaultdict 会更好:
from collections import defaultdict
a = defaultdict(dict)
a["01/03/2001"]["zz"]=3
a["01/01/2001"]["un"]=1
a["01/02/2001"]["aa"]=2
a["01/01/2001"]["nn"]=1
a["01/02/2001"]["bb"]=2
a["01/03/2001"]["rr"]=3
# a is now a dict of dicts, each key is a date and each value is a dict of all
# subkey-values
# print out in date order
for k,v in sorted(a.items()):
# for each subdict, print key=value in sorted key order
print k, ' '.join("%s=%s" % (kk,vv) for kk,vv in sorted(v.items()))
印刷:
01/01/2001 nn=1 un=1
01/02/2001 aa=2 bb=2
01/03/2001 rr=3 zz=3
编辑:
啊! 我的错,您希望 k=v 值按插入顺序显示,因此您需要 OrderedDict 的 defaultdict:
from collections import defaultdict, OrderedDict
a = defaultdict(OrderedDict)
a["01/01/2001"]["un"]=1
a["01/01/2001"]["nn"]=1
a["01/02/2001"]["aa"]=2
a["01/02/2001"]["bb"]=2
a["01/03/2001"]["zz"]=3
a["01/03/2001"]["rr"]=3
# print out in date order
for k,v in sorted(a.items()):
# for each subdict, print key=value in as-inserted key order, so no sort requred
print k, ' '.join("%s=%s" % (kk,vv) for kk,vv in v.items())
印刷:
01/01/2001 un=1 nn=1
01/02/2001 aa=2 bb=2
01/03/2001 zz=3 rr=3