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.
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
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.