nk14 nk14 - 1 year ago 96
Python Question

Use more than 1 condition in python for loops

I want to call a python for loop with two conditions 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 Source
 for files,script in TEMPLATE_FILE.items():

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()):
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download