我可以用键从字典中删除一个值吗?函数del_contact
应该只使用联系人的名字来删除contact
,但不幸的是,我有字典和值,但没有键。如何解决这个问题?
my_contacts = {
1: {
"Name": "Tom Jones",
"Number": "911",
"Birthday": "22.10.1995",
"Address": "212 street"
},
2: {
"Name": "Bob Marley",
"Number": "0800838383",
"Birthday": "22.10.1991",
"Address": "31 street"
}
}
def add_contact():
user_input = int(input("please enter how many contacts you wanna add: "))
index = len(my_contacts) + 1
for _ in range(user_input):
details = {}
name = input("Enter the name: ")
number = input("Enter the number: ")
birthday = input("Enter the birthday")
address = input("Enter the address")
details["Name"] = name
details["Number"] = number
details["Birthday"] = birthday
details["Address"] = address
my_contacts[index] = details
index += 1
print(my_contacts)
def del_contact():
user_input = input("Please enter the name of the contact you want to delete: ")
my_contacts.pop(user_input)
add_contact()
print(my_contacts)
问题是我的字典键是1
或Name
,我希望能够仅使用Name
的值来删除联系人。
基本上你能做的就是迭代字典并只保存不包含用户名的键。
下面的代码可以达到这个目的:
my_contacts = {1: {"Name": "Tom Jones",
"Number": "911",
"Birthday": "22.10.1995",
"Address": "212 street"},
2: {"Name": "Bob Marley",
"Number": "0800838383",
"Birthday": "22.10.1991",
"Address": "31 street"}
}
user_input = "Tom Jones"
my_contacts = {key: value for key, value in my_contacts.items() if value["Name"] != user_input}
这里有两个步骤:
- 查找与 匹配的键/值对
- 删除找到的密钥
如果你只删除一个条目(即使有多个匹配项),它们总是可以组合在一起:
def del_contact():
user_input = input("Please enter the name of the contact you want to delete: ")
for k, v in my_contacts.items(): # Need both key and value, we test key, delete by value
if v["Name"] == user_input:
del my_contacts[k]
break # Deleted one item, stop now (we'd RuntimeError if iteration continued)
else:
# Optionally raise exception or print error indicating name wasn't found
如果您可能删除多个条目,并且必须在适当的位置操作,那么您将拆分步骤(因为在更改键集的同时继续迭代dict
是非法的):
def del_contact():
user_input = input("Please enter the name of the contact you want to delete: ")
to_delete = [k for k, v in my_contacts.items() if v["Name"] == user_input]
if not to_delete:
# Optionally raise exception or print error indicating name wasn't found
for k in to_delete:
del my_contacts[k]
或者,如果您愿意替换原始的dict
,而不是对其进行就地修改,则可以将多次删除的情况一行写成:
def del_contact():
global my_contacts # Assignment requires explicitly declared use of global
user_input = input("Please enter the name of the contact you want to delete: ")
my_contacts = {k: v for k, v in my_contacts.items() if v["Name"] != user_input} # Flip test, build new dict
# Detecting no matches is more annoying here (it's basically comparing
# length before and after), so I'm omitting it
我想这就是你需要的,希望这对你有帮助。
代码:
my_contacts = {1: {"Name": "Tom Jones",
"Number": "911",
"Birthday": "22.10.1995",
"Address": "212 street"},
2: {"Name": "Bob Marley",
"Number": "0800838383",
"Birthday": "22.10.1991",
"Address": "31 street"}
}
def add_contact():
user_input = int(input("please enter how many contacts you wanna add: "))
index = len(my_contacts) + 1
for _ in range(user_input):
details = {}
name = input("Enter the name: ")
number = input("Enter the number: ")
birthday = input("Enter the birthday")
address = input("Enter the address")
details["Name"] = name
details["Number"] = number
details["Birthday"] = birthday
details["Address"] = address
my_contacts[index] = details
index += 1
print(my_contacts)
add_contact()
print(my_contacts)
def del_contact():
user_input = input("Please enter the name of the contact you want to delete: ")
values = [key for key in my_contacts.keys() if user_input in my_contacts[key].values()]
for value in values:
my_contacts.pop(value)
del_contact()
print(my_contacts)
输入:{1: {'Name': 'Tom Jones', 'Number': '911', 'Birthday': '22.10.1995', 'Address': '212 street'}, 2: {'Name': 'Bob Marley', 'Number': '0800838383', 'Birthday': '22.10.1991', 'Address': '31 street'}, 3: {'Name': 'myname', 'Number': '1233455', 'Birthday': '12-12-22', 'Address': 'blabla street'}}
Please enter the name of the contact you want to delete: Bob Marley
输出:{1: {'Name': 'Tom Jones', 'Number': '911', 'Birthday': '22.10.1995', 'Address': '212 street'}, 3: {'Name': 'myname', 'Number': '1233455', 'Birthday': '12-12-22', 'Address': 'blabla street'}}
由于索引用作字典的键,因此range
函数可以如下使用:
def del_contact():
user_input = input("Please enter the name of the contact you want to delete: ")
for i in range(1,len(my_contacts)+1):
if my_contacts[i]['Name'] == user_input:
del my_contacts[i]
break
如果可以有多个相同名称的联系人需要删除,则删除break语句。
但是正如在评论中提到的,没有必要使用索引作为字典的键。您可能会遇到的一个潜在错误是,如果删除了名称为Tom Jones
的第一个条目,则dict
的长度为1,只有一个键- 2。然后当您尝试添加更多联系人时,当您检查字典index = len(my_contacts) + 1
的长度时,由于长度为1,索引将为2。因此,my_contacts[index] = details
将使用密钥2或"Name": "Bob Marley"
更新联系人,而不是添加新联系人。