I need to iterate through a dictionary of lists, not knowing how many lists the dictionary will have, but still pair off each list value with any other list value produced from another key in the dictionary (if another one exists). I have the following code:
def loop_rec(codes, currentcode={}):
if len(codes.keys())>1:
for key in sorted(codes):
codespop = dict(codes)
loop = codespop.pop(key)
for x in loop:
currentcode[key]=x
loop_rec(codespop,currentcode)
break
else:
for key in codes.keys():
loop = codes[key]
for x in loop:
currentcode[key]=x
print currentcode
So if I have the following dictionary:
codes = {"coarse":range(4),"fine":range(2)}
I get this result:
>>> loop_rec(codes)
{'fine': 0, 'coarse': 0}
{'fine': 1, 'coarse': 0}
{'fine': 0, 'coarse': 1}
{'fine': 1, 'coarse': 1}
{'fine': 0, 'coarse': 2}
{'fine': 1, 'coarse': 2}
{'fine': 0, 'coarse': 3}
{'fine': 1, 'coarse': 3}
This is a brute force method and would like a more "Pythonic" way of doing this. I searched around a lot for something equivalent, but most methods don't result in the coarse and fine values being together for each iteration. Also would prefer it loop through coarse first, but the sorted command isn't working.
EDIT: Just realized the sorted command is working, the printout just isn't sorted. I don't care if it is printed in order.