pythonpython-2.7

Printing dictionary in a While Loop


I have been looking around to see if anyone has actually done it but couldn't find it so hoping I can get some help here.

newDict = {'Jan':31, 'Feb':29, 'Mar':31, 'Apr':30, 'May':31, 'Jun':30, 'Jul':31, 'Aug':30}

I created this dict and I want to use a while loop to output it this way:

Jan 31
Feb 29
Mar 31
Apr 30
May 31
Jun 30
Jul 31
Aug 30

I am able to do it with a for loop, just curious how it can be done with a while loop.


Solution

  • You can make your dictionary an iterator calling iteritems (Python 2.x), or iter on the items() (Python 3.x)

    # Python 2.x
    from __future__ import print_function
    items = newDict.iteritems()
    
    # Python 3.x
    items = iter(newDict.items())
    
    while True:
        try: 
            item = next(items)
            print(*item)
        except StopIteration:
            break
    

    Note: We're importing print_function on Python 2.x because print would be a statement instead of a function, and hence the line print(*item) would actually fail