5

所以,我是一名正在尝试学习python的php程序员。我有一个我想要排序的字典。我把它们变成了 OrderedDict。他们完美地排序,原始字典看起来像这样。这只是一个 3 维数组对吗?

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中做到这一点。有人可以帮忙吗?

4

3 回答 3

5

dict.items()使用or方法遍历键和值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
于 2013-09-25T16:25:12.267 回答
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 的 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
于 2013-09-25T17:42:23.180 回答
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())])
于 2013-09-26T18:06:30.060 回答