Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
382 views
in Technique[技术] by (71.8m points)

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.

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]) + '
')

    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:

stock: 10000

estate: 2000

work: 80000

investment: 30000

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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. 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]) + '
')  # 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...