14

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
  • 31,737
  • 7
  • 30
  • 50
oren_isp
  • 649
  • 1
  • 6
  • 19

2 Answers2

19

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
  • 31,737
  • 7
  • 30
  • 50
13
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
  • 6,381
  • 11
  • 37
  • 66