簡體   English   中英

如何將選定的字典數據導出到python中的文件中?

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

現在,當我檢查這個函數時,在 export_incomes 中,如果income_types 在費用中: TypeError: unhashable type: 'list' 我不確定我在這里做錯了什么。

我確實創建了一個收入字典,其中收入類型為鍵,收入值為值。

迭代給定的收入字典,根據給定的收入類型(字符串列表)過濾,並導出到文件。

將給定的收入類型從給定的收入字典導出到給定的文件。

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

首先,你以費用開始你的問題,但以收入結束,代碼在參數中也有收入,所以我會用收入。

其次,錯誤說明了答案。 “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)

如果我做出了任何錯誤的假設或弄錯了您的意圖,請告訴我。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM