Create Dictionary From Dataframe Values

Viewed 443

I would like to create a dictionary where the keys are values from one column of a data frame and the values are from another column in the corresponding row.

So here is an example dataframe:

df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))
df.head()

    A   B   C   D
0   34  99  78  0
1   31  47  44  22
2   53  38  11  27
3   86  84  81  87
4   57  4   23  46

And I want to get a dictionary like this, with the A values as the keys and the C values as the dictionary values:

{34: 78, 31: 44, 53: 11, 86: 81,57: 23}

How would you go about doing this?

2 Answers

You can create a dict from an array of tuples with keys and tuples. So you can use the dict constructor straightforward here after converting the values to tuples with the zip function

In [12]: dict(zip(df['A'], df['C']))                                                                                                                                                                               
Out[12]: {34: 78, 31: 44, 53: 11, 86: 81, 57: 23}
Related