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

2

80

How to iterate a dict with enumerate such that I could unpack the index, key and value at the time of iteration?

Something like:

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

I want to iterate through the keys and values in a dictionary called mydict and count them, so I know when I'm on the last pair.

Limon answered 12/2, 2017 at 21:53 Comment(5)
What exactly are you trying to do with indices on a dict?Chronon
I'm printing the dict to a file, so I need to know when to insert a newline.Limon
Does the index matters for that? At the end of the loop you know that you're done with the dict and can insert a newline.Chronon
I insert a comma between each value (it's a .csv) and I need to know when to insert a comma and when to insert a newline.Limon
do not re-invent the wheel, use csv built-in module, it has dicts supportTigrinya
B
119

Instead of using mydict, you should be using mydict.items() with enumerate as:

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

Sample 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

Explanation:

  • enumerate() returns an iterator object which contains tuples in the format: [(index, list_element), ...]
  • dict.items() returns an iterator object (in Python 3.x. It returns list in Python 2.7) in the format: [(key, value), ...]
  • On combining together, enumerate(dict.items()) will return an iterator object containing tuples in the format: [(index, (key, value)), ...]
Brittney answered 12/2, 2017 at 21:54 Comment(0)
U
1

It's also possible to use itertools.count to count along.

from itertools import count
for i, (k, v) in zip(count(), mydict.items()):
    # do something

This is useful especially if you want the counter to be fractional numbers. For example,

mydict = dict(zip(range(3), range(10, 13)))

for i, (k, v) in zip(count(step=0.5), mydict.items()):
    print(f"index={i:<3}, key={k}, value={v}")
    
# index=0  , key=0, value=10
# index=0.5, key=1, value=11
# index=1.0, key=2, value=12
Upstage answered 22/2, 2023 at 0:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.