亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

無法編寫條件來更新Python中的字典值

無法編寫條件來更新Python中的字典值

冉冉說 2023-07-18 15:26:27
請幫忙!如何在現有代碼中編寫條件,該代碼將進行如下檢查。請看評論區。我無法在字典/列表中附加值。我需要寫/更改什么?當用戶返回主菜單并使用相同的密鑰文件再次運行加密過程但以不同的名稱保存加密文件時。用戶可以使用相同的密鑰創建盡可能多的加密文件。我的嘗試:import Encryptfrom collections import defaultdictkey_value_dict = {}def encrypt_file():    try:        txtfile = input("Your plain txt file that you want to encrypt : ")        encrypt_file = input("Directory to save the encrypted file : ")        key = input("Key for encryption : ")        # process for encryption        Encrypt.encrypt_file(txtfile, encrypt_file, key)        # ----------------------------------------------------------------        key_value_dict = defaultdict(list, {key: encrypt_file})        print(key_value_dict)        key_value_dict [key].append(encrypt_file)        print(key_value_dict )        # --------------------------------------------------------------------    except FileNotFoundError:        print("File Not Found!")def menu():    selection = True    while selection:        print("""MAIN MENU:[1] Encrypt files using existing keys.[2] Exit.        """)        try:              selection = input("Please select : ")            if selection == "1":                encrypt_file()  # call function            elif selection == "2":                print("\n[4] Keys are used for encryption:", "\n", key_value_dict)                selection = None            else:                print("\n Invalid selection! Try again")        except ValueError:              print("\n Exception: Invalid user input!")# Main functionif __name__ == '__main__':    menu()  
查看完整描述

1 回答

?
Qyouu

TA貢獻1786條經驗 獲得超11個贊

如果我理解正確的話,我認為你不需要 defaultdict


嘗試這個:


# define this first outside the function like you have

encrypt_key_value_dict = {}


# Within your code block, get rid of the assignment to default dict

if encrypt_key_value_dict[key]:

    encrypt_key_value_dict.append(encrypt_file)

else:

    encrypt_key_value_dict[key] = [encrypt_file]

我無法從您的代碼中看到您的密鑰在哪里傳遞等,但我相信您可以弄清楚。


查看完整回答
反對 回復 2023-07-18
  • 1 回答
  • 0 關注
  • 124 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號