Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Programming
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Databases
Mail Systems
openSolaris
Eclipse Documentation
Techotopia.com
Virtuatopia.com
Answertopia.com

How To Guides
Virtualization
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Windows
Problem Solutions
Privacy Policy

  




 

 

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.

 
 
  Published under the terms of the Python License Design by Interspire