首页 > 解决方案 > 将两个列表组合成字典时,只有最后一个对象被传递给字典

问题描述

嗨,我正在尝试将从 csv 文件创建的两个列表合并到一个字典中。但 dict 仅包含列表中的最后一个对象。我究竟做错了什么?

在此处输入图像描述

标签: pythonlistdictionary

解决方案


您每次在构建字典时都会覆盖密钥。以下代码将在列表中包含借方和贷方的值。打印时应该是这样的:{"credit" : [...], "debit": [...]}.

credit_list = []
debit_list = []
combination = zip(dc_list, amount_list)
for key, value in combination:
    if key == "credit":
        credit_list.append(value)
    elif key == "debit":
        debit_list.append(value)

mydict = {"credit": credit_list, "debit": debit_list}

注意:以上是如何在您的问题中发布代码的方式。


推荐阅读