1

using Excel table data, Want to create a nested dictionary as follows:

    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:

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

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     |  
Bala
  • 648
  • 5
  • 15

1 Answers1

0

you should transpose the dataframe before converting it into dictionary.

df.T.to_dict()
Dan911
  • 1