nk14 nk14 - 1 month ago 6
Python Question

how to use more than 1 condition in for loops

I have a simple coding here, but get stuck when I try to read in the 'files' and 'script'. How should the for loops be like actually?to call 2 conditions at one time.

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"


Thanks,

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)