简体   繁体   English

如何使用 python 中的 pandas 从 excel 数据创建嵌套字典?

[英]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 lbl_name id ID english英语 tamil泰米尔语 hindi印地语
lbl101 lbl101 file文件 File文件 tamil_file泰米尔语文件 hindi_file印地语文件
lbl102 lbl102 accounts帐户 Accounts账户 tamil_accounts泰米尔语帐户 hindi_accounts印地语帐户
lbl103 lbl103 inventory存货 Inventory存货 tamil_inventory tamil_inventory hindi_inventory印地文库存
lbl104 lbl104 manufacture生产 Manufacture生产 tamil_manufact 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM