如何将Excel文件转换为嵌套的Python字典?

3

我有一个非常具体的类似这样的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字典?


到目前为止,我尝试使用sheet2dict和pandas库,但在Excel表中,id是字典中的一个。因此,我不知道如何确保第一列始终设置为

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

x = ws.xlsx_to_dict(path = file_path)

print(x)
1个回答

1

由于我没有Excel文件,所以我使用您在问题中提到的字典item_map创建了DataFrame,如下:

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

你可以使用pandas.read_excel将表格导入为DataFrame。记得将索引设置为'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'}}

谢谢,不过在将我的表作为数据框导入后,它自动将键指定为0、1、2。我该如何将其指定为Excel文件中的第一列? - inspiring
实际上我已经想通了:df.set_index('id', inplace=True)会将id设置为键。 - inspiring
是的,它有效吗?我通过重新创建您的DataFrame来测试我的代码。我使用了您在问题中提到的字典,如下所示:df = pd.DataFrame(item_map).T,然后将索引设置为:df.index.name = 'id'。 - Shivam Roy
@ShivamRoy:初始示例仅提供平面结构,即{0: {'Id': 751, 'Name': 'Test 1', 'Price': 125, 'check_type': 'Check 1'}。请根据OP的要求更新答案,提供带有嵌套字典的可行解决方案。 - IODEV
@IODEV 实际上,输出看起来很平淡,但它与 OP 要求的格式完全相同。在发布代码之前,我尝试了一下,确实返回了嵌套字典。如果我没有理解您的问题,我很抱歉,您是指行的对齐吗?如果您运行代码,您会发现输出与 OP 要求的嵌套格式相同。 - Shivam Roy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接