Reputation: 91
I have xlsx file like this
travel_df = pd.read_excel('../Data/TopMart.xlsx')
data = travel_df.to_dict('records')
the data look like this
parent_name_1 parent_name_2 parent_name_3
A1 B1 C1
A2 B2 C2
A3 B3 C3
A4 B4 C4
I want to make dict like this from that:
cat = {
A1 : [B1, C1],
A2 : [B2, C2],
A3 : [B3, C3],
A4 : [B4, C4],
}
what is the best way to do that
Upvotes: 0
Views: 163
Reputation: 170
cat = travel_df.set_index("parent_name_1").T.to_dict(orient="list")
Upvotes: 4
Reputation: 337
I don't know if it is the best way, but you can try:
import pandas
if __name__ == "__main__":
xls = pandas.read_excel("test.xls")
data = {xls.iloc[i][0]: list(xls.iloc[i][1:].values) for i in range(len(xls))}
Assuming that your first column has unique keys.
Upvotes: 0
Reputation: 102
import pandas as pd
my_data = pd.DataFrame({
'A': ['A1', 'A2', 'A3', 'A4'],
'B': ['B1', 'B2', 'B3', 'B4'],
'C': ['C1', 'C2', 'C3', 'C4']
})
result = my_data.set_index('A').to_dict('index')
{key: list(value.values()) for key, value in result.items()}
{'A1': {'B': 'B1', 'C': 'C1'},
'A2': {'B': 'B2', 'C': 'C2'},
'A3': {'B': 'B3', 'C': 'C3'},
'A4': {'B': 'B4', 'C': 'C4'}}
{'A1': ['B1', 'C1'],
'A2': ['B2', 'C2'],
'A3': ['B3', 'C3'],
'A4': ['B4', 'C4']}
Upvotes: 1
Reputation: 3113
Maybe there is a better function to do this directly, but I couldn't find it... But the df.to_dict('split')
gets something that helps, and is easy enough to finish the way. This is what split gives us:
{'index': [0, 1, 2, 3],
'columns': ['parent_name_1', 'parent_name_2', 'parent_name_3'],
'data': [['A1', 'B1', 'C1'],
['A2', 'B2', 'C2'],
['A3', 'B3', 'C3'],
['A4', 'B4', 'C4']]}
The data
item here sort of has what we want, sort of...
l = df.to_dict('split')['data']
cat = dict()
for n in l:
cat.update({n[0]:[n[1],n[2]]})
At the end of that, cat
looks just how (I think) you want.
Upvotes: 1