-1

I am looking for a way to get the current loop iteration while looping though a key, value pair of dictionary items.

currently i am using enumerate() to split it into iteration, tuple(key, value) however this requires using tuple indexes to split it back out.

mydict = {'fruit':'apple', 'veg':'potato', 'sweet':'haribo'}

for i, kv in enumerate(mydict.items()):
    print(f"iteration={i}, key={kv[0]}, value={kv[1]}")
#>>> iteration=0, key=fruit, value=apple
#>>> iteration=1, key=veg, value=potato
#>>> iteration=2, key=sweet, value=haribo

what I am looking for is a better method to replace the following:

i = 0
for key, value in mydict.items():
     print(f"iteration={i}, key={key}, value={value}")
     i+=1
#>>> iteration=0, key=fruit, value=apple
#>>> iteration=1, key=veg, value=potato
#>>> iteration=2, key=sweet, value=haribo

I do not want to give up user assigned keywords for the dictionary just to include iteration. I am hoping to find a solution similar to (psudo-code):

for key, value, iteration in (tuple(mydict.items()), list(mydict.keys()).index(k)):
Scott Paterson
  • 392
  • 2
  • 17

1 Answers1

1

Just put the (key, value) in brackets:

mydict = {'fruit':'apple', 'veg':'potato', 'sweet':'haribo'}

for i, (key, value) in enumerate(mydict.items()):
    print(f"iteration={i}, key={key}, value={value}")
Lukas Hebing
  • 107
  • 2