Get dictionary from a dataframe

I have a dataframe like below:

df = pd.DataFrame({
'Aapl': [12, 5, 8],
'Fs': [18, 12, 8],
'Bmw': [6, 18, 12],
'Year': ['2020', '2025', '2030']

})

I want a dictionary like:

d={'2020':[12,18,16],
   '2025':[5,12,18],
   '2030':[8,8,12]
  }

I am not able to develop the whole logic:

lst = [list(item.values()) for item in df.to_dict().values()]
dic={}
for items in lst:
    for i in items[-1]:
        dic[i]=#2000 will hold all the 0th values of other lists and so on 

Is there any easier way using pandas ?

>Solution :

Convert Year to index, transpose and then in dict comprehension create lists:

d = {k: list(v) for k, v in df.set_index('Year').T.items()}
print (d)
{'2020': [12, 18, 6], '2025': [5, 12, 18], '2030': [8, 8, 12]}
        

Or use DataFrame.agg:

d = df.set_index('Year').agg(list, axis=1).to_dict()
print (d)
{'2020': [12, 18, 6], '2025': [5, 12, 18], '2030': [8, 8, 12]}
    

Leave a Reply