Home > Blockchain >  How to assign number in loop as key and list item as value
How to assign number in loop as key and list item as value

Time:10-09

I have 7 letters, `alphabets = ['a', 'b', 'c', 'd', 'e', 'f', 'g']. Am iterating over a loop as follows and assigning the number to the dictionary as key, I want 35 assigned a, 40 = b, 45 = c, 50 = d, 55 = e, 60 = f, 65 = g. From here I want it to go back to A (as it's reached the end of the loop) and similarly for other numbers while incrementing, how can this be achieved?

pos = {}
alphabets = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
for number in range(35, 75, 5):
    pos[number]  = #?

CodePudding user response:

itertools.cycle() is helpful for things like this. It will keep cycling over the letters until you stop asking for more. Combined with zip you get a simple one-liner. This works because zip will stop iterating after the shortest iterator stops, which in this case is the range:

from itertools import cycle

pos = dict(zip(range(35, 75, 5), cycle('abcdefg')))
# {35: 'a', 40: 'b', 45: 'c', 50: 'd', 55: 'e', 60: 'f', 65: 'g', 70: 'a'}

CodePudding user response:

Here is a more beginner-friendly alternative to Mark's answer

counter = 0

pos = {}
alphabets = ['a', 'b', 'c', 'd', 'e', 'f', 'g']

for number in range(35, 75, 5):
    pos[number] = alphabets[counter % len(alphabets)]
    counter  = 1

CodePudding user response:

Why not just zip the 2 iterables:

dict(zip(range(35, 76, 5), alphabets*2))

{35: 'a', 40: 'b', 45: 'c', 50: 'd', 55: 'e', 60: 'f', 65: 'g', 70: 'a', 75: 'b'}
  • Related