简体   繁体   English

如何将 excel 文件转换为嵌套的 python 字典?

[英]How do I convert an excel file into a nested python dictionary?

I have a very specific Excel sheet that looks like this:我有一个非常具体的 Excel 表,如下所示:

Excel工作表图片

I am trying to convert it to a Python dictionary like this:我正在尝试将其转换为 Python 字典,如下所示:

item_map = {
    "1609755": {
        "name": "test 1",
        "price": 125,
        "check_type": "check 1"
    },
    "1609756": {
        "name": "test 2",
        "price": 2500,
        "check_type": "check 2"
    },
    "1609758": {
        "name": "test 3",
        "price": 2400,
        "check_type": "check 3"
    }
}

My question is: How do I convert a excel sheet to a Python dictionary?我的问题是:如何将 excel 表转换为 Python 字典?


So far I tried using the library sheet2dict and also pandas, however in the excel sheet, the id is a key in the dictionary.到目前为止,我尝试使用库 sheet2dict 和 pandas,但是在 excel 表中, id是字典中的key As a result, I am quite stumped on how to ensure that the first column is ALWAYS set as a key.结果,我对如何确保始终将第一列设置为键感到非常困惑。

from sheet2dict import Worksheet
ws = Worksheet()
file_path = 'test.xlsx'

x = ws.xlsx_to_dict(path = file_path)

print(x)

Since I do not have the Excel file, I created the DataFrame using your dictionary mentioned in the question ie, item_map likewise:由于我没有 Excel 文件,因此我使用问题中提到的字典创建了 DataFrame,即item_map同样:

df = pd.DataFrame(item_map).T    #Had to take a Transpose
df.index.name = 'id'

You can import your table as a DataFrame using pandas.read_excel .您可以使用pandas.read_excel将表作为 DataFrame 导入。 Remember to set the index as 'id'.请记住将索引设置为“id”。

df = pd.read_excel('file_path')
df.index.name = 'id'

Then, use this code:然后,使用以下代码:

item_map = {}

for index, row in list(df.iterrows()):
    item_map[index] = dict(row)

print(item_map)

Output: Output:

{'1609755': {'name': 'test 1', 'price': 125, 'check_type': 'check 1'},
'1609756': {'name': 'test 2', 'price': 2500, 'check_type': 'check 2'},
'1609758': {'name': 'test 3', 'price': 2400, 'check_type': 'check 3'}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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