Search code examples
pythondictionaryindexingdictionary-comprehension

Dict Comprehension with 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_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)}


Solution

  • 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)))