How to iterate `dict` with` enumerate` and unpack the index, key and value along with iteration

How to iterate dictwith enumerateso that I can decompress the index, key and value during iteration?

Sort of:

for i, (k, v) in enumerate(mydict):
    # some stuff

I want to iterate over the keys and values ​​in a dictionary called mydictand count them, so I know when I am at the last.

+4
source share
1 answer

Instead, mydictyou should use mydict.items()with enumeratelike:

for i, (k, v) in enumerate(mydict.items()):
    # your stuff

Example example:

mydict = {1: 'a', 2: 'b'}
for i, (k, v) in enumerate(mydict.items()):
    print("index: {}, key: {}, value: {}".format(i, k, v))

# which will print:
# -----------------
# index: 0, key: 1, value: a
# index: 1, key: 2, value: b

Explanations:

  • enumerate returns an iterator object that contains tuples in the format: [(index, list_element), ...]
  • dict.items()returns an iterator object (in Python 3.x. It returns listin Python 2.7) in the format:[(key, value), ...]
  • enumerate(dict.items()) -, : [(index, (key, value)), ...]
+15

Source: https://habr.com/ru/post/1669529/


All Articles