【问题标题】:How do I convert an excel file into a nested python dictionary?如何将 excel 文件转换为嵌套的 python 字典?
【发布时间】:2021-04-21 18:42:51
【问题描述】:

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

我正在尝试将其转换为这样的 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 是字典中的 key。结果,我很困惑如何确保第一列始终设置为键。

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

x = ws.xlsx_to_dict(path = file_path)

print(x)

【问题讨论】:

    标签: python excel dictionary


    【解决方案1】:

    由于我没有 Excel 文件,因此我使用问题中提到的字典创建了 DataFrame,即 item_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'}}
    

    【讨论】:

    • 谢谢您,但是似乎在将我的表作为数据框导入后,它会自动将键指定为 0、1、2。如何将其指定为 Excel 文件中的第一列?跨度>
    • 其实我想通了:df.set_index('id', inplace=True) 会设置它,所以id是关键。
    • 是的,它有效吗?我通过重新创建您的 DataFrame 来测试我的代码。我同样使用了您在问题中提到的字典: df = pd.DataFrame(item_map) .T 然后将索引设置为: df.index.name = 'id'
    • @ShivamRoy:最初的例子只给出了一个平面结构,即{0: {'Id': 751, 'Name': 'Test 1', 'Price': 125, 'check_type': 'Check 1'}, 请按照OP的要求,用一个带有嵌套字典的工作解决方案来更新答案。
    • @IODEV 输出实际上看起来很平坦,但它与 OP 要求的格式完全相同。我在发布之前尝试了代码,它确实返回了嵌套字典。对不起,如果我不理解您的问题,是关于线条的对齐方式吗?如果您运行代码,您会发现输出与 OP 要求的嵌套格式相同。
    猜你喜欢
    • 2023-03-11
    • 2019-10-25
    • 1970-01-01
    • 2021-05-18
    • 2021-06-14
    • 1970-01-01
    • 2023-02-23
    • 1970-01-01
    • 2019-11-07
    相关资源
    最近更新 更多