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?
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
I think rather than OrderedDict, you will be better off with a 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()))
Prints:
01/01/2001 nn=1 un=1
01/02/2001 aa=2 bb=2
01/03/2001 rr=3 zz=3
EDIT:
Ah! My bad, you want the k=v values shown in insertion order, so you need a defaultdict of OrderedDict's:
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())
Prints:
01/01/2001 un=1 nn=1
01/02/2001 aa=2 bb=2
01/03/2001 zz=3 rr=3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With