19

I have the dataframe

    ID   A   B   C
0   p    1   3   2
1   q    4   3   2
2   r    4   0   9  

And I want to create a dict where ID is the keys and B is the values so it will be:

d["q"] = 3 , d["r"] = 0

What is the best way to do so?

It is different than the supposed duplicate becasue I want single value per key and not a list

Mayank Porwal
  • 33,470
  • 8
  • 37
  • 58
oren_isp
  • 729
  • 1
  • 7
  • 22

2 Answers2

27

Something like this:

In [27]: df
Out[27]: 
  ID  A  B  C
0  p  1  3  2
1  q  4  3  2
2  r  4  0  9

In [30]: df.set_index('ID',inplace=True)
In [31]: df
Out[31]: 
    A  B  C
ID         
p   1  3  2
q   4  3  2
r   4  0  9

In [33]: df.to_dict()['B']
Out[33]: {'p': 3, 'q': 3, 'r': 0}
Mayank Porwal
  • 33,470
  • 8
  • 37
  • 58
15
df = pd.DataFrame([['p',1,3,2],['q',4,3,2],['r',4,0,9]], columns=['ID','A','B','C'])
df=df[['ID','A','B','C']]

df

  ID  A  B  C
0  p  1  3  2
1  q  4  3  2
2  r  4  0  9

your_dict = dict(zip(df.ID, df.B))

your_dict
 {'p': 3, 'q': 3, 'r': 0}
cph_sto
  • 7,189
  • 12
  • 42
  • 78
  • In my case, each value in ID has multiple values, I want the output to be {'p':[1,2,3,4], 'q':[3,4,5,6,7],'r':[9,8,4]}. How shall I achieve this? – sunakshi132 Nov 12 '22 at 06:47