|
7.5 Looping Techniques
When looping through dictionaries, the key and corresponding value can
be retrieved at the same time using the items() method.
>>> knights = {'gallahad': 'pure', 'robin': 'brave'}
>>> for k, v in knights.items():
... print k, 'the', v
...
gallahad the pure
robin the brave
To loop over two or more sequences at the same time, the entries
can be paired with the zip() function.
>>> questions = ['name', 'quest', 'favorite color']
>>> answers = ['lancelot', 'the holy grail', 'blue']
>>> for q, a in zip(questions, answers):
... print 'What is your %s? It is %s.' % (q, a)
...
What is your name? It is lancelot.
What is your quest? It is the holy grail.
What is your favorite color? It is blue.
|
|