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

如何调用嵌套字典的键?通过值使用update()更新字典遇问题

问题解答

一、调用嵌套字典中的键

嵌套字典需要通过外层键 + 内层键逐层访问取值,比如获取Mohamed的生日:

birthday = contacts["Mohamed"]["birthday"]
print(birthday)  # 输出 24.11.1990

如果要遍历所有嵌套键值对,可使用items()方法同时获取外层键和内层字典:

for outer_key, inner_dict in contacts.items():
    print(f"联系人:{outer_key}")
    for inner_key, value in inner_dict.items():
        print(f"  {inner_key}: {value}")

二、通过值定位并使用update()更新字典

你的原代码问题在于硬编码了"Mohamed",无法动态匹配用户输入的联系人。正确逻辑是:先根据输入的name值找到对应外层键,再对该外层键关联的内层字典用update()修改内容。

修正后的示例代码

contacts = {"Mohamed": {"name": "Mohamed Sayed", "number": "0123565665", "birthday": "24.11.1990", "address": "Ginnheim 60487"},
            "Ahmed": {"name": "Ahmed Sayed", "number": "0123456789", "birthday": "06.06.1990", "address": "India"}}

def edit_contact():
    user_input = input("请输入要编辑的联系人姓名:")
    # 遍历外层键和对应的内层联系人字典
    for outer_key, inner_dict in contacts.items():
        if user_input == inner_dict["name"]:
            # 示例:固定更新电话号码,也可扩展为用户自定义字段
            inner_dict.update({"number": "0987654321"})
            print("联系人已更新:", contacts[outer_key])
            return
    print("未找到该联系人")

# 调用测试
edit_contact()

扩展支持自定义修改字段

如果需要让用户自主选择修改的字段和新值,可调整函数:

def edit_contact():
    user_input = input("请输入要编辑的联系人姓名:")
    for outer_key, inner_dict in contacts.items():
        if user_input == inner_dict["name"]:
            field = input("请输入要修改的字段(如number/birthday/address):")
            new_value = input(f"请输入{field}的新值:")
            inner_dict.update({field: new_value})
            print("更新后的联系人:", contacts[outer_key])
            return
    print("未找到该联系人")

内容的提问来源于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.09 17:45:31