nk14 nk14 - 1 month ago 6
Python Question

Use more than 1 iterable in a python for loop

I want to call a python for loop with two iterables like this:

TEMPLATE_FILE = { 'a': 'power', 'b': 'voltage', 'c': 'current' }
for (script in TEMPLATE_FILE.values()) and (files in TEMPLATE_FILE.keys()):
print 'script: ',script
print 'files: ',files
print "\n"


But that is a syntax error, how can I do it?

Answer
 for files,script in TEMPLATE_FILE.items():
    print(files,scripts)

is the construction you're looking for.

(in python 2 there's an iteritems which is removed in python 3 so for small dictionaries items is OK and portable)

of course you can do:

for files in TEMPLATE_FILE:
    scripts = TEMPLATE_FILE[files]

but that's not as efficient as you're hashing the key at each iteration, whereas you could get the values without that. Reserve hashing for random access cases.

Note that you can iterate through sorted keys like this (frequent question):

 for files,script in sorted(TEMPLATE_FILE.items()):
    print(files,scripts)