如何将选定的字典数据导出到python文件中? [英] how to export selected dictionary data into a file in python?

查看:164
本文介绍了如何将选定的字典数据导出到python文件中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在,当我检查此功能时,export_incomes
如果费用中的income_types:
TypeError:无法散列的类型:'list'
我不确定我在这里做错了什么。

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

I did create an incomes dictionary with income_types as key and income_value as value.

迭代给定的收入字典,过滤器

Iterates over the given incomes dictionary, filters based on the given income types (a list of strings), and exports to a file.

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

Exports the given income types from the given incomes dictionary to the given file.

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 h项目和值应该在单独的行上:

If this is the income list that should be in txt if a user inputs stock, estate, work and investment, each should item and value should be on a separate line:

库存:10000

房地产:2000

工作:80000

投资:30000

推荐答案

首先,您从以下问题开始费用,但以收入结尾,并且代码中的参数中也包含收入,因此我将收入作为参数。

First, you start your question with expenses but ends with incomes and the code also has incomes in the parameters so I'll go with the income.

第二,错误说明了答案。 expense_types(income_types);是清单和费用(收入);是一本字典。您正在尝试在字典中查找列表(不可散列)。

Second, the error says the answer. "expense_types(income_types)" is a list and "expenses(incomes)" is a dictionary. You're trying to find a list (not hashable) in a dictionary.

因此,为了使代码正常工作:

So to make your code work:

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)

如果我做出了错误的假设或您的意图错误,请让我知道。

If I made any wrong assumption or got your intention wrong, pls let me know.

这篇关于如何将选定的字典数据导出到python文件中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆