2

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?

Sam44
  • 47
  • 1
  • 7
  • 2
    Does this answer your question? [Convert a Pandas DataFrame to a dictionary](https://stackoverflow.com/questions/26716616/convert-a-pandas-dataframe-to-a-dictionary) – Youness Saadna Aug 14 '20 at 14:50

2 Answers2

4

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}
maow
  • 2,712
  • 1
  • 11
  • 25
2

Another approach Series.to_dict and DataFrame.set_index

df.set_index('A')['C'].to_dict()
# {34: 78, 31: 44, 53: 11, 86: 81, 57: 23}
ansev
  • 30,322
  • 5
  • 17
  • 31