Ask Your Question
3

How can one go over a key/value map object by repeatedly executing its elements?

asked 2022-09-26 11:00:00 +0000

ladyg gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2022-10-07 02:00:00 +0000

huitzilopochtli gravatar image

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
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-09-26 11:00:00 +0000

Seen: 10 times

Last updated: Oct 07 '22