3

I,m recently started learning python, so I'm sure that are many things that I don't know that may be quite simple to solve. However, searching through a lot of questions I couldn't find an answer to this one.

Is it possible to iterate an variable in a dictionary comprehension statement?

While searching for an answer I've found this:

{ _key : _value(_key) for _key in _container }

Wich, I'm now aware, is a way of looping inside the comprehension, but for this to work for me, I need to be able to iterate the value for each '_key' in the '_container'.

For a very basic example:

alphabet = 'abcdefghijklmnopqrstuvwxyz'

x = 1

alpha_numbers = {char : x for char in alphabet}

I would like 'x' to be 'x += 1' for each 'char' in the 'alphabet' container. But every way I try to iterate it, inside the dictionary comprehension, returns a 'Invalid Syntax' error.

So, is it possible to do it? Or there is a better way to make it?

Thanks in advance.

Hugo bler
  • 31
  • 2

2 Answers2

5

You can use dict and enumeratepassing x as the starting value:

alphabet = 'abcdefghijklmnopqrstuvwxyz'

dct = dict(enumerate(alpahbet, x)) # start=x i.e 1

Demo:

In [43]: print dict(enumerate(alphabet,1))
{1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e', 6: 'f', 7: 'g', 8: 'h', 9: 'i', 10: 'j', 11: 'k', 12: 'l', 13: 'm', 14: 'n', 15: 'o', 16: 'p', 17: 'q', 18: 'r', 19: 's', 20: 't', 21: 'u', 22: 'v', 23: 'w', 24: 'x', 25: 'y', 26: 'z'}

Or using enumerate with a dict comp:

 dct = {i:k for i,k in enumerate(alphabet,x)}

To get the letters as keys reverse the order of i and k:

dct = {k:i for i,k in enumerate(alphabet,x)}

Or using itertools.count with dict and zip:

from itertools import count
dct = dict(zip(alphabet, count(x)))

Or range, len and zip:

 dct = dict(zip(alphabet, range(x, len(alphabet)+x)))
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
1

For this case, in particular, consider using indices: {alphabet[i]:i+1 for i in range(len(alphabet))}.

That said, you cannot update variables inside a list, set or dictionary comprehension. If you'd like to do that, use a normal for loop or while loop and dictionary[key] = value to add within that loop.

Heman Gandhi
  • 1,343
  • 9
  • 12