【问题标题】:how to export selected dictionary data into a file in python?如何将选定的字典数据导出到python中的文件中?
【发布时间】:2020-10-07 17:01:26
【问题描述】:

现在,当我在 export_incomes 中检查此功能时 如果在费用中收入类型: 类型错误:不可散列类型:“列表” 我不确定我在这里做错了什么。

我确实创建了一个收入字典,其中收入类型作为键,收入值作为值。

遍历给定的收入字典,根据给定的收入类型(字符串列表)进行过滤,然后导出到文件。

将给定收入字典中的给定收入类型导出到给定文件。

def export_incomes(incomes, income_types, file):
    final_list = []

    for u, p in expenses.items():
        if expense_types in expenses:
            final_list.append(':'.join([u,p]) + '\n')

    fout = open(file, 'w')
    fout.writelines(final_list)
    fout.close()

如果这是用户输入股票、房地产、工作和投资时应该在 txt 中的收入列表,则每个项目和价值都应该在单独的行中:

库存:10000

房产:2000

工作:80000

投资:30000

【问题讨论】:

    标签: python file dictionary


    【解决方案1】:

    首先,您的问题从费用开始,但以收入结尾,代码中的参数也包含收入,所以我将使用收入。

    其次,错误说明了答案。 “expense_types(income_types)”是一个列表,“expenses(incomes)”是一个字典。您正在尝试在字典中查找列表(不可散列)。

    所以要让你的代码工作:

    def export_incomes(incomes, income_types, file):
        items_to_export = []
    
        for u, p in incomes.items():
            if u in income_types:
                items_to_export.append(': '.join([u,p]) + '\n')  # whitespace after ':' for spacing
        
        with open(file, 'w') as f:
            f.writelines(items_to_export)
    

    如果我做了任何错误的假设或误解了你的意图,请告诉我。

    【讨论】:

      猜你喜欢
      • 2018-11-06
      • 2023-01-20
      • 2023-01-18
      • 2019-06-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多