Filter a dictionary with matrix row and columns

Viewed 38

I have a dictionary {(0, 0): [(1, 0), (0, 1)], (0, 1): [(1, 1), (0, 0), (0, 2)], (0, 2): [(1, 2), (0, 1), (0, 3)], (0, 3): [(1, 3), (0, 2), (0, 4)], (0, 4): [(1, 4), (0, 3), (0, 5)], (0, 5): [(1, 5), (0, 4), (0, 6)]}, the keys are coordinates or (row, col) tuples that correlate to a matrix, the values are the neighbors or the adjacent (row, col) pairs that are near that node so for example if (0, 0) is the most top left element in the grid the nodes near it are (0, 1) and (1, 0) because they are adjacent. My question is how can I filter out this dictionary so that instead of the (row, col) tuples I'll have the elements corresponding to that position on the grid so lets say (0, 0):[(1, 0), (0, 1)] is going to be equal to my_matrix[0][0]:[my_matrix[1][0], my_matrix[0][1]] and so on for the whole dictionary

1 Answers

Using a dict comprehension with a nested list comprehension to loop over the neighbors:

matrix = [[i+j for i in range(10)] for j in range(10)]
d = {(0, 0): [(1, 0), (0, 1)], (0, 1): [(1, 1), (0, 0), (0, 2)], (0, 2): [(1, 2), (0, 1), (0, 3)], (0, 3): [(1, 3), (0, 2), (0, 4)], (0, 4): [(1, 4), (0, 3), (0, 5)], (0, 5): [(1, 5), (0, 4), (0, 6)]}
print({
    matrix[key[0]][key[1]]:
    [matrix[coord[0]][coord[1]] for coord in coords] 
    for key, coords in d.items()
})

Output:

{0: [1, 1], 1: [2, 0, 2], 2: [3, 1, 3], 3: [4, 2, 4], 4: [5, 3, 5], 5: [6, 4, 6]}
Related