Reputation: 895
Say I have the following dataframe:
myDF = pd.DataFrame([['A','red'],['B','green'],
['C','orange'],['D','purple']], columns = ['letter','color'])
How can I reformat this into a nested dictionary, such that the key of the outer dictionary is taken from the letter column, the key of the inner dictionary is taken from the color column-name, and that value of the inner dictionary is taken from the color column...
key | value
-----------------------------
A {color: red}
B {color: green}
C {color: orange}
D {color: purple}
I have tried various takes on the df.to_dict
without success. I have managed to get it in the right format if I export as csv, and then import using DictReader
, but this is obviously long-winded.
myFile = csv.DictReader(open('file.csv'))
output = {}
for row in myFile:
key = row.pop('letter')
if key in output:
pass
output[key] = row
Upvotes: 0
Views: 55
Reputation: 316
You should try this
import pandas as pd
myDF = pd.DataFrame([['A','red'],['B','green'],
['C','orange'],['D','purple']], columns = ['letter','color'])
mydict = {}
for i in range(0,len(myDF)):
mydict[myDF['letter'][i]] = myDF['color'][i]
print(mydict)
Answer:-{'A': 'red', 'B': 'green', 'C': 'orange', 'D': 'purple'}
Upvotes: 0
Reputation: 36
Try this:
myDF.set_index('letter').to_dict('index')
Output:
{'A': {'color': 'red'}, 'B': {'color': 'green'}, 'C': {'color': 'orange'}, 'D': {'color': 'purple'}}
Upvotes: 2
Reputation: 150
That will do the job:
output_dict = dict()
for (letter, color) in df.values:
output_dict[letter] = {'color': color}
Upvotes: 0
Reputation: 6181
You can achieve it by setting letter
as index and setting the orient property -
myDF.set_index("letter").to_dict(orient="index")
Upvotes: 1
Reputation: 10960
Use dict comprehension
{row.letter: {'color': row.color} for row in myDF.itertuples()}
Output
{'A': {'color': 'red'}, 'B': {'color': 'green'}, 'C': {'color': 'orange'}, 'D': {'color': 'purple'}}
Upvotes: 1