Dict Comprehension with index

Viewed 188

How to obtain the equivalent result of this code using dictionary comprehension?

dict_sq = dict()
i = 0
for y in range(grid_height):
    for x in range(grid_height):
        dict_sq[i] = (x, y)
        i = i + 1

{0: (0, 0), 1: (1, 0), 2: (2, 0), 3: (0, 1), 4: (1, 1), 5: (2, 1), 6: (0, 2), 7: (1, 2), 8: (2, 2)}

3 Answers

this should do what you want (iterating over x and y and calculating i = x + grid_height * y from those):

grid_height = 3
dct = {x + grid_height * y:
           (x, y) for y in range(grid_height) for x in range(grid_height)}

or you could go the other way round (iterating over i and getting x = i//grid_height and )y = i%grid_height from that):

dct = {i: (i//grid_height, i%grid_height) for i in range(grid_height**2)}

As an alternative method from the other answer, I used list comprehension with enumerate to map it to a dict.

dict(enumerate((x, y) for y in range(grid_height) for x in range(grid_height)))

Use itertools.product to create one iterator iterating over both ranges, then enumerate to add indexes to that iterator:

from itertools import product

dict_sq = {i: (x, y)
           for (i, (y, x)) in enumerate(product(range(grid_height), range(grid_height)))}

Since the ranges are the same, you could use repeat=2 instead of writing the range twice:

from itertools import product

dict_sq = {i: (x, y)
           for (i, (y, x)) in enumerate(product(range(grid_height), repeat=2))}
Related