简体   繁体   English

通过python中的用户输入删除和更新字典键/值

[英]Deleting and Updating Dictionary key/value through user input in python

Hello i'm trying to play around with python dictionaries i was able to create a dictionary through user input but i can't find a way to update and delete a dictionary by taking a user input.您好,我正在尝试使用 python 词典,我能够通过用户输入创建词典,但是我找不到通过用户输入来更新和删除词典的方法。

dictionary = {}
ele = int(input("How many element u want? "))

for i in range(ele):
    inn = input("Key: ")
    nam = input("Value: ")
    dictionary.update({inn:nam})

print(dictionary)

this is my code to create a dictionary through user input now i need help with deleting and updating a dictionary through user input if possible.这是我通过用户输入创建字典的代码,现在我需要帮助,如果可能的话,我需要通过用户输入删除和更新字典。

"deleting" dictionary: “删除”字典:

dictionary = {1:"hi"}
delete = input("do you want to delete the contents of the dictionary? (y/n").lower()
if delete in ["y","yes"]: dictionary = {}

making this a bit more compact:使它更紧凑一点:

dictionary = {1:"hi"}
if input("do you want to delete the contents of the dictionary? (y/n): ").lower() in ["y","yes"]: dictionary = {}
print(dictionary)

>> do you want to delete the contents of the dictionary? (y/n): y

>> {}

explanation:解释:

using the input function (as i believe you know about) transformed the input to lowercase and then checked if it was in a list of acceptable answers.使用输入函数(我相信你知道)将输入转换为小写,然后检查它是否在可接受的答案列表中。 dictionary = {} sets the dictionary back to containing nothing dictionary = {}将字典设置回不包含任何内容


updating dictionary:更新字典:

def updateDict(dictionary):
    choice = int(input("do you want to (1) add/update an item to the dictionary or (2) remove an item: (1 or 2):  "))
    if choice in [1,2]:
        if choice == 1:
            dictionary[input("key: ")] = input("value: ")
        else:
            dictionary.pop(input("key: "))
    else:
        print("invalid choice")

Keep in mind: this only adds string values, you can always add a choice to specify what data type is being entered.请记住:这只会添加字符串值,您始终可以添加一个选项来指定正在输入的数据类型。

To delete the dictionary you just redefine it as empty要删除字典,您只需将其重新定义为空

dictionary = {}

For deleting an item from a dictionary use要从字典中删除项目,请使用

del dictionary[key]

To update a value you can use要更新您可以使用的值

dictionary[key] = value

You can set the key as a variable that the user inputs to select the key to be deleted or updated.您可以将 key 设置为用户输入的变量,以选择要删除或更新的 key。

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

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