how to enumerate OrderedDict in python

user2773013 picture user2773013 · Sep 25, 2013 · Viewed 9.2k times · Source

So, I'm a php programmer who is trying to learn python. i have a dict of dict that i want sorted. I turned them into OrderedDict. They sort perfectly, The original dict look like this. This is just a 3 dimensional array right?

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

I can convert them into OrderedDict, and want to present them in the following format

"01/01/2001" un=1 nn=1
"01/02/2001" aa=2 bb=2
"01/03/2001" zz=3 rr=3

I can write a simple loop in php to go through this associative array, but i can't figure out how to do it in python. Could someone help?

Answer

Martijn Pieters picture Martijn Pieters · Sep 25, 2013

Loop through the keys and values using the dict.items() or dict.iteritems() methods; the latter lets you iterate without building an intermediary list of key-value pairs:

for date, data in a.iteritems():
    print date,
    for key, value in data.iteritems():
        print '{}={}'.format(key, value),
    print

Looping directly over dictionaries gives you keys instead; you can still access the values by using subscription:

for date in a:
    print date,
    for key in a[date]:
        print '{}={}'.format(key, a[date][key]),
    print