Ask Your Question

Revision history [back]

One can use a for loop to iterate over the key/value pairs in a map object. For example,

my_dict = {'a': 1, 'b': 2, 'c': 3}

for key, value in my_dict.items():
    print(key, value)

This will print:

a 1
b 2
c 3

Alternatively, one can also use a while loop and the iter() function to get an iterator for the map object:

my_dict = {'a': 1, 'b': 2, 'c': 3}

it = iter(my_dict.items())

while True:
    try:
        key, value = next(it)
        print(key, value)
    except StopIteration:
        break

This will also print:

a 1
b 2
c 3