如何在Python嵌套字典中按需添加键:父键存在时添加至对应层级,不存在时添加至主字典
解决方案:根据父键存在性添加嵌套键
嘿,我来帮你搞定这个需求!核心思路是先找到父键vegetarian所在的嵌套字典层级,找到就往这个层级加新键,找不到就直接加到主字典顶层。
首先咱们优化一下查找逻辑——你原来的递归函数在处理keys列表时会有回溯问题(比如进入某个子字典没找到目标键时,keys里的元素没被移除,导致后续查找的路径错误),所以换个更直接的方式:直接返回目标键所在的字典对象,后续操作起来更省心。
完整代码实现
def find_parent_dict(dictionary, target_key): # 先检查当前字典是否包含目标键 if target_key in dictionary: return dictionary # 递归遍历所有子字典查找 for key, value in dictionary.items(): if isinstance(value, dict): found_dict = find_parent_dict(value, target_key) if found_dict is not None: return found_dict # 遍历完都没找到,返回None return None # 你的原始菜单字典 menu = {'dinner': {'chicken':'good', 'beef':'average', 'vegetarian':{ 'tofu':'good', 'salad':{ 'caeser':'bad', 'italian':'average'} }, 'pork':'bad'} } # 要添加的新键和对应值 new_key = 'green_veg' new_value = 'excellent' # 查找父键所在的字典 parent_dict = find_parent_dict(menu, 'vegetarian') # 根据查找结果添加新键 if parent_dict is not None: parent_dict[new_key] = new_value print(f"已将{new_key}添加到vegetarian层级下") else: menu[new_key] = new_value print(f"未找到vegetarian,已将{new_key}添加到顶层") # 打印结果验证 print(menu)
代码说明
find_parent_dict函数:递归遍历嵌套字典,找到包含目标键vegetarian的字典并返回;如果遍历完所有层级都没找到,就返回None。- 主逻辑:调用查找函数后,根据返回结果判断——如果找到父字典,就把
green_veg加到这个字典里;如果没找到,就直接作为顶层键加到menu中。
测试两种场景
父键存在的情况(你的原始
menu):
运行后vegetarian字典会新增'green_veg': 'excellent',结果如下:{'dinner': {'chicken': 'good', 'beef': 'average', 'vegetarian': {'tofu': 'good', 'salad': {'caeser': 'bad', 'italian': 'average'}, 'green_veg': 'excellent'}, 'pork': 'bad'}}父键不存在的情况(比如把
menu里的vegetarian删掉):
运行后menu顶层会新增'green_veg': 'excellent',结果如下:{'dinner': {'chicken': 'good', 'beef': 'average', 'pork': 'bad'}, 'green_veg': 'excellent'}
内容的提问来源于stack exchange,提问作者Sumit
相关产品推荐
相关产品推荐

