You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Name值删除Python字典中的联系人条目

通过姓名删除联系人的解决方案

你的问题出在my_contacts的键是数字ID,而不是联系人姓名,直接用姓名调用pop()自然找不到对应的键——pop()需要传入字典的键(这里是1、2这类数字),而不是子字典里的Name值。

要实现通过姓名删除,需要先遍历字典找到对应姓名的键,再执行删除操作。以下是修改后的del_contact函数:

def del_contact():
    user_input = input("Please enter the name of the contact you want to delete: ")
    # 遍历字典的键值对,转成list避免遍历中修改字典引发错误
    for contact_id, details in list(my_contacts.items()):
        if details["Name"] == user_input:
            my_contacts.pop(contact_id)
            print(f"联系人 {user_input} 已删除")
            return
    # 如果遍历完没找到
    print(f"未找到姓名为 {user_input} 的联系人")

额外说明

  • 使用list(my_contacts.items())是因为直接遍历原字典的items()时,删除元素会导致迭代器异常,转成列表后就可以安全遍历并修改原字典。
  • 如果存在多个同名联系人,上面的代码只会删除第一个匹配的。如果需要删除所有同名联系人,去掉return语句即可,还可以统计删除数量:
def del_contact():
    user_input = input("Please enter the name of the contact you want to delete: ")
    deleted_count = 0
    for contact_id, details in list(my_contacts.items()):
        if details["Name"] == user_input:
            my_contacts.pop(contact_id)
            deleted_count += 1
    if deleted_count > 0:
        print(f"共删除 {deleted_count} 个名为 {user_input} 的联系人")
    else:
        print(f"未找到姓名为 {user_input} 的联系人")

修改后的完整代码

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: ")
    deleted_count = 0
    for contact_id, details in list(my_contacts.items()):
        if details["Name"] == user_input:
            my_contacts.pop(contact_id)
            deleted_count += 1
    if deleted_count > 0:
        print(f"共删除 {deleted_count} 个名为 {user_input} 的联系人")
    else:
        print(f"未找到姓名为 {user_input} 的联系人")


# 示例调用(可根据需求调整)
# add_contact()
# del_contact()
# print(my_contacts)

内容的提问来源于stack exchange,提问作者Mohamed Sayed

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 10:15:46