面试题答案
一键面试nested_dict = {'person': {'name': 'Bob', 'hobbies': ['reading', 'running']}}
# 添加新爱好到hobbies列表
nested_dict['person']['hobbies'].append('swimming')
# 添加新键值对到person字典
nested_dict['person']['city'] = 'New York'
print(nested_dict)
在嵌套字典更新过程中需要注意的要点:
- 确保外层键存在:在访问或修改嵌套字典内层的值之前,要确保外层的键已经存在。如果外层键不存在,直接访问内层键会引发
KeyError
。 - 数据结构类型匹配:比如添加新爱好到
hobbies
列表时,要确认hobbies
确实是列表类型。如果类型不匹配,可能导致运行时错误。例如,如果hobbies
被错误赋值为一个字符串,调用append
方法就会报错。