无法编写条件来更新Python中的字典值

请帮忙!如何在现有代码中编写条件,该代码将进行如下检查。请看评论区。我无法在字典/列表中附加值。我需要写/更改什么?

  1. 当用户返回主菜单并使用相同的密钥文件再次运行加密过程但以不同的名称保存加密文件时。用户可以使用相同的密钥创建尽可能多的加密文件。

我的尝试:

import Encrypt

from collections import defaultdict


key_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 function

if __name__ == '__main__':

    menu()  


冉冉说
浏览 107回答 1
1回答

Qyouu

如果我理解正确的话,我认为你不需要 defaultdict尝试这个:# define this first outside the function like you haveencrypt_key_value_dict = {}# Within your code block, get rid of the assignment to default dictif encrypt_key_value_dict[key]:    encrypt_key_value_dict.append(encrypt_file)else:    encrypt_key_value_dict[key] = [encrypt_file]我无法从您的代码中看到您的密钥在哪里传递等,但我相信您可以弄清楚。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python