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

2024-10-01 15:44:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个非常具体的Excel表格,如下所示:

Excel Sheet Picture

我正在尝试将其转换为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"
    }
}

我的问题是:如何将excel工作表转换为Python字典?


到目前为止,我尝试使用library sheet2dict和pandas,但是在excel工作表中,id是字典中的key。因此,如何确保第一列始终设置为键,我感到非常困惑

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

x = ws.xlsx_to_dict(path = file_path)

print(x)

Tags: pathnametest字典wschecktypexlsx
1条回答
网友
1楼 · 发布于 2024-10-01 15:44:04

由于我没有Excel文件,因此我使用问题中提到的词典创建了数据框,即,item\u map同样:

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

可以使用pandas.read_excel将表作为数据帧导入。请记住将索引设置为“id”

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

然后,使用以下代码:

item_map = {}

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

print(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'}}

相关问题 更多 >

    热门问题