[英]How to Create a nested dictionary, from excel data using pandas in python?
using Excel table data, Want to create a nested dictionary as follows:使用Excel表数据,想创建嵌套字典如下:
dict_mainmenu_items = {"id" : {"lbl101":"file" ,"lbl102":"accounts" ,"lbl103":"inventory","lbl104":"manufacture"},
"english" : {"lbl101":"File" ,"lbl102":"Accounts" ,"lbl103":"Inventory","lbl104":"Manufacture"},
"tamil" : {"lbl101":"tamil_file","lbl102":"tamil_accounts","lbl103":"tamil_inventory","lbl104":"tamil_manu"},
"hindi" : {"lbl101":"hindi_file","lbl102":"hindi_accounts","lbl103":"hindi_inventory","lbl104":"hindi_manuf"}}
try to solve the problem by using pandas, and code as follows:尝试使用pandas解决问题,代码如下:
import pandas as pd
file_path = r'C:/Users/Asus/Desktop/Documents/pyhton_dict_example.xlsx'
df = pd.read_excel(file_path)
df.set_index('lbl_name',inplace=True)
print(df.to_dict(orient='index'))
its produce the following result:它产生以下结果:
{'lbl101': {'id': 'file', 'english': 'File', 'tamil': 'tamil_file', 'hindi': 'Hindi_File'}, 'lbl102': {'id': 'accounts', 'english': 'Accounts', 'tamil': 'tamil_accounts', 'hindi': 'Hindi_Accounts'}, 'lbl103': {'id': 'inventory', 'english': 'Inventory', 'tamil': 'tamil_inventory', 'hindi': 'Hindi_Inventory'}, 'lbl104': {'id': 'manufacture', 'english': 'Manufacture', 'tamil': 'tamil_manuf', 'hindi': 'Hindi_Manufacture'}}
Excel Table Excel表
lbl_name ![]() |
id ![]() |
english![]() |
tamil![]() |
hindi![]() |
---|---|---|---|---|
lbl101 ![]() |
file![]() |
File![]() |
tamil_file![]() |
hindi_file![]() |
lbl102 ![]() |
accounts![]() |
Accounts![]() |
tamil_accounts![]() |
hindi_accounts![]() |
lbl103 ![]() |
inventory![]() |
Inventory![]() |
tamil_inventory ![]() |
hindi_inventory![]() |
lbl104 ![]() |
manufacture![]() |
Manufacture![]() |
tamil_manufact ![]() |
hindi_manu![]() |
| lbl_name | id |english |tamil |hindi |
|------------------------------------------------------|---------------|
| lbl101 | file | File |tamil_File |hindi_file |
| lbl102 | accounts | Accounts |tamil_accounts |hindi+accounts | |
| lbl103 | inventory | Inventory |tamil_inventory |hindi_inventory|
| lbl104 | manufacture| Manufacture|tamil_manufact| |hindi_manu |
you should transpose the dataframe before converting it into dictionary.您应该先将 dataframe 转置为字典。
df.T.to_dict()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.