person = {
"name": "Luca",
"surname": "Rossi",
"age": 25
}
operations = ("adding", "modifying", "deleting", "read person", "exit")
def start():
operation = input("What you wanna do? ")
if operation == operations[0]:
x = input("Add a key:value separated by a comma: ")
add(x.split(","))
elif operation == operations[1]:
x = input("Select a key:value and modify it: ")
modify(x.split(":"))
elif operation == operations[2]:
x = input("Select a key:value and delete it: ")
delete(x)
elif operation == operations[3]:
print(person)
elif operation == operation[4]:
exit()
def add(param):
key= param[0]
value= param[1]
person[key] = value
print(person)
def modify(param):
key = param[0]
value = param[1]
person[key] = value
print(person)
def delete(param):
key = param
if key in person:
del person[key]
print(person)
else:
print(f"The key '{key}' does not exist.")
while True:
start()
为什么删除不起作用?添加和修改都很好,就像我写的那样。我正在尝试不同的删除方法,但没有人可以。
还尝试了 pop、remove 和 del,但我是初学者,我不明白为什么它不起作用。 前两个功能对我来说很简单...... 有什么帮助吗?预先感谢
代码中删除函数的问题与您传递删除输入的方式有关。在删除函数中,您将整个输入 (x) 作为单个参数传递,但输入函数返回一个字符串,并且您希望将其拆分为键和值。
这是删除功能的更正版本:
def delete(param):
key = param[0].strip() # Strip to remove any leading/trailing whitespaces
if key in person:
del person[key]
print(person)
else:
print(f"The key '{key}' does not exist.")
现在,当您调用delete(x)时,它将正确分割输入字符串并使用第一部分作为删除的键。此外,strip() 方法用于删除键中的任何前导或尾随空格。
例如,如果您输入“姓名”进行删除,则会正确删除字典中的“姓名”键。
以下是更正后的删除功能的工作原理:
x = input("Select a key to delete: ")
delete(x.split(":"))
输入密钥(例如“姓名”),它应该从人员字典中删除相应的条目。