所以,我是一个试图学习python的php程序员。我有一个dict的词典,我想要排序。我把它们变成了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
我可以将它们转换为OrderedDict,并希望以下列格式呈现它们
"01/01/2001" un=1 nn=1
"01/02/2001" aa=2 bb=2
"01/03/2001" zz=3 rr=3
我可以在php中编写一个简单的循环来完成这个关联数组,但我无法弄清楚如何在python中完成它。有人可以帮忙吗?
答案 0 :(得分:3)
使用dict.items()
或dict.iteritems()
方法遍历键和值;后者允许您迭代而不构建键值对的中间列表:
for date, data in a.iteritems():
print date,
for key, value in data.iteritems():
print '{}={}'.format(key, value),
print
直接在字典上循环可以为您提供密钥;您仍然可以使用订阅来访问这些值:
for date in a:
print date,
for key in a[date]:
print '{}={}'.format(key, a[date][key]),
print
答案 1 :(得分:2)
我认为而不是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的默认值:
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
答案 2 :(得分:0)
试用此代码。
a = {
"01/01/2001": {"un": 1, "nn": 1}, \
"01/02/2001": {"aa": 2, "bb": 2}, \
"01/03/2001": {"zz": 3, "rr": 3}
}
class decor(object):
def __init__(self, a):
self.a = a
def __call__(self, fun):
def wrapper(key, _list):
print key, ' '.join(["{}={}".format(ele, self.a[key][ele]) \
for ele in _list
])
fun(key)
return wrapper
@decor(a)
def main_fun(key):
pass
for key in sorted(a.keys()):
main_fun(key, [inner_key for inner_key in sorted(a[key].keys())])