Use more than 1 iterable in a python for loop
This question already has an answer here:
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)
To access key, value in dictionary you can do like this.
For Python 2.x:
for files,script in TEMPLATE_FILE.iteritems():
For Python 3.x:
for files,script in TEMPLATE_FILE.items():
Or you can also do this, independent of python version:
for files in TEMPLATE_FILE:
script = TEMPLATE_FILE[files]
#print(files, script)
The last bit has the drawback of re-hashing the keys each time as suggested by @Jean-FrançoisFabre.
You just want to iterate over a dictionary and get the key and its value at each iteration.
for file_ in TEMPLATE_FILE:
script = TEMPLATE_FILE[file_]
or
for file_, script in TEMPLATE_FILE.items():
...
链接地址: http://www.djcxy.com/p/30360.html
上一篇: 如何访问我的字典