0

As a learner of python, I am confused about some functions. Someone, please make a normal loop from this comprehensive loop. Here items is a dictionary.

items={1:'a',2:'b',4:'d',5:'e'}

items = {k: v for k, v in enumerate(items.values(), start=1)}

I want to make a normal for loop of the upper comprehensive loop. I have tried but don't get the exact result. Look here:

for k,v in enumerate(items.values(),start =1):
                  `items ={k:v}`

Help me.

sadik
  • 50
  • 1
  • 8
  • Did you mean `items.items()` instead of `items.values()`? – chepner Aug 12 '21 at 15:44
  • 1
    Also, you aren't building up a new dict; you are just repeatedly replacing the previous value of `items` with a new one. – chepner Aug 12 '21 at 15:45
  • This [animation](https://stackoverflow.com/questions/18072759/list-comprehension-on-a-nested-list/45079294#45079294) shows the reverse process. It might still be useful here. – quamrana Aug 12 '21 at 15:45
  • Yes chepner I understand what was wrong I am doing. Thanks all. – sadik Aug 12 '21 at 15:58

1 Answers1

2

You can't write directly back into items with for loop. The list comprehension works because it creates a new dictionary and replaces the old one. While for-loop can't do that by itself. So you need to create a new dictionary and add key-values to it:

new_dict = {}
for k, v in enumerate(items.values(), start=1):
    new_dict[k] = v

if needed replace old one with new one afterwards:

items = new_dict
Yevhen Kuzmovych
  • 10,940
  • 7
  • 28
  • 48