Search code examples
pythonindexingdictionary-comprehension

Dict comprehension using index


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_width):
        dict_sq[(x, y)] = i
        i = i + 1

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

I obtained the same result but with keys and values reversed, using this approach:

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

But I need the index as values instead of the keys. There is an elegant way using enumerate?


Solution

  • Use a dict comprehension to reverse keys and values in one go:

    >>> {
    ...     (x, y): i
    ...     for i, (x, y)
    ...     in enumerate((x, y) for x in range(grid_height) for y in range(grid_height))
    ... }
    {(0, 0): 0, (0, 1): 1, (0, 2): 2, (1, 0): 3, (1, 1): 4, (1, 2): 5, (2, 0): 6, (2, 1): 7, (2, 2): 8}