简体   繁体   English

如何将选定的字典数据导出到python中的文件中?

[英]how to export selected dictionary data into a file in python?

Right now when I check this function, in export_incomes if income_types in expenses: TypeError: unhashable type: 'list' I am not sure what I did wrong here.现在,当我检查这个函数时,在 export_incomes 中,如果income_types 在费用中: TypeError: unhashable type: '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()

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:如果这是用户输入股票、房地产、工作和投资时应在 txt 中的收入列表,则每个应项目和价值应在单独的行上:

stock: 10000库存:10000

estate: 2000庄园:2000

work: 80000工作量:80000

investment: 30000投资: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.首先,你以费用开始你的问题,但以收入结束,代码在参数中也有收入,所以我会用收入。

Second, the error says the answer.其次,错误说明了答案。 "expense_types(income_types)" is a list and "expenses(incomes)" is a dictionary. “expense_types(income_types)”是一个列表,“expenses(incomes)”是一个字典。 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.如果我做出了任何错误的假设或弄错了您的意图,请告诉我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM