Skip to content
Advertisement

convert dataframe row to dict

I have datarame like the sample data below. I’m trying to convert one row from the dataframe in to a dict like the desired output below. But when I use to_dict I get the indice along with the column value. Does anyone know how to get convert the row to a dict like the desired output? Any tips greatly appreciated.

Sample data:

print(catStr_df[['Bottle Volume (ml)', 'Pack']][:5])

      Bottle Volume (ml)  Pack
595                  750    12
1889                 750    12
3616                1000    12
4422                 750    12
5022                 750    12


Code:

v = catStr_df[catStr_df['Item Number']==34881][['Bottle Volume (ml)', 'Pack']]
.drop_duplicates(keep='first').to_dict()

v

Output:

{'Bottle Volume (ml)': {9534: 1000}, 'Pack': {9534: 12}}

Desired output:

{'Bottle Volume (ml)': 1000, 'Pack': 12}

Advertisement

Answer

Try adding .to_dict('records')[0] to the row you want

catStr_df[catStr_df['Item Number']==34881].to_dict('records')[0]
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement