Skip to content
Advertisement

Convert pandas DataFrame to dict where each value is a list of values of multiple columns

Let’s say I have the DataFrame

filename size inverse similarity
123.txt  1    2       34
323.txt  3    1       44
222.txt  4    1       43

I want to create a dictionary in the form

{'123.txt': [1, 2, 34],
 '323.txt': [3, 1, 44],
 '222.txt': [4, 1, 43]}

Solutions I have found deal with the case of creating a dict with single values using something like

df.set_index('Filename')['size'].to_dict()

Advertisement

Answer

Set 'filename' as the index, take the transpose, then use to_dict with orient='list':

my_dict = df.set_index('filename').T.to_dict(orient='list')

The resulting output:

{'323.txt': [3, 1, 44], '222.txt': [4, 1, 43], '123.txt': [1, 2, 34]}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement