Python data frame to dictionary by index variables (i,j)

I’d like to convert a Python data frame (pandas or other) into a dictionary but the key should be the position (i,j). For example, have a dataframe like:

col1 col2 col3
7 1 2
8 9 6
4 7 5

I’d like to return a dictionary with the key as the position of the value, so the 2nd row, 3rd column would be stored in a dictionary like below.

{(1,2): 6}

Is there a built-in function for this? Or do I need to iterate over the entire data frame? I have not yet found a way to get the position into a dictionary. From other threads, I’ve seen that you can extract the index with something like this (dataframe called ‘df’):

df.stack().index.tolist()

Answer

Let’s use a list comprehension to make generating the keys simple.

data = [[1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]]

data_dict = {}

for key in [(x, y) for x in range(3) for y in range(3)]:
    data_dict[key] = data[key[1]][key[0]]

Python 2.7+ provides a more elegant solution to this with dictionary comprehensions.

data = [[1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]]

data_dict = {(x, y): data[y][x] for x in range(3) for y in range(3)}