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

Python字典键值编辑删除及联系人管理程序问题求助

基于Python字典的联系人管理程序完整实现

以下是满足所有需求的联系人管理程序代码,解决了添加、删除、编辑、列出、查看功能的常见问题:

def main():
    contacts = {}
    while True:
        print("\n=== 联系人管理系统 ===")
        print("1. 添加新联系人")
        print("2. 删除联系人")
        print("3. 编辑联系人")
        print("4. 列出所有联系人")
        print("5. 查看联系人详情")
        print("6. 退出")
        
        choice = input("请输入操作编号: ")
        
        if choice == "1":
            add_contact(contacts)
        elif choice == "2":
            delete_contact(contacts)
        elif choice == "3":
            edit_contact(contacts)
        elif choice == "4":
            list_contacts(contacts)
        elif choice == "5":
            view_contact(contacts)
        elif choice == "6":
            print("退出程序...")
            break
        else:
            print("无效输入,请重新选择")

def add_contact(contacts):
    name = input("请输入联系人姓名: ").strip()
    if name in contacts:
        print("该联系人已存在!")
        return
    phone = input("请输入联系电话: ").strip()
    email = input("请输入邮箱地址: ").strip()
    contacts[name] = {"phone": phone, "email": email}
    print(f"联系人 {name} 添加成功!")

def delete_contact(contacts):
    name = input("请输入要删除的联系人姓名: ").strip()
    if name in contacts:
        del contacts[name]
        print(f"联系人 {name} 删除成功!")
    else:
        print("该联系人不存在!")

def edit_contact(contacts):
    name = input("请输入要编辑的联系人姓名: ").strip()
    if name not in contacts:
        print("该联系人不存在!")
        return
    print("保留原信息请直接回车")
    new_phone = input(f"原电话: {contacts[name]['phone']}, 输入新电话: ").strip()
    new_email = input(f"原邮箱: {contacts[name]['email']}, 输入新邮箱: ").strip()
    if new_phone:
        contacts[name]['phone'] = new_phone
    if new_email:
        contacts[name]['email'] = new_email
    print(f"联系人 {name} 编辑成功!")

def list_contacts(contacts):
    if not contacts:
        print("暂无联系人")
        return
    print("\n=== 联系人列表 ===")
    for idx, name in enumerate(contacts.keys(), 1):
        print(f"{idx}. {name} - 电话: {contacts[name]['phone']}")

def view_contact(contacts):
    name = input("请输入要查看的联系人姓名: ").strip()
    if name in contacts:
        print(f"\n=== {name} 的详情 ===")
        print(f"电话: {contacts[name]['phone']}")
        print(f"邮箱: {contacts[name]['email']}")
    else:
        print("该联系人不存在!")

if __name__ == "__main__":
    main()

关键功能实现细节

  • 添加联系人:先校验姓名唯一性,避免重复存储;用嵌套字典结构,外层键为联系人姓名,内层存储电话、邮箱等扩展信息。
  • 删除联系人:先判断目标联系人是否存在,防止因键不存在抛出异常。
  • 编辑联系人:支持部分字段更新,无需重新输入全部信息,提升操作效率。
  • 列出联系人:遍历字典键值对,简洁展示核心信息;空列表时给出友好提示。
  • 查看联系人:精准查找指定联系人,展示完整详情。

内容的提问来源于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 14:25:15