首页 > 解决方案 > 在 Python 中使用 keypath 创建嵌套字典

问题描述

有一个具有多级键的嵌套字典。要求是:

例如,这是字典:

{
    "animal": {
        "dog": {
            "type": "beagle"
        }
    },
    "man": {
        "name": "john",
        "age": 36
    },
    "plant": {
        "fruit": {
            "apple": {
                "type": "gala"
            }
        }
    }
}

以下是更新值或附加新嵌套键路径的函数:

appendDict(["man", "name"], "daniel", json_dict)
appendDict(["computer", "laptop", "maker"], "hp", json_dict)

这是预期的结果:

{
    "animal": {
        "dog": {
            "type": "beagle"
        }
    },
    "man": {
        "name": "daniel",
        "age": 36
    },
    "plant": {
        "fruit": {
            "apple": {
                "type": "gala"
            }
        }
    },
    "computer": {
        "laptop": {
            "maker": "hp"
        }
    }    
}

我的问题是如何实现 appendDict() 函数以支持要求?

到目前为止,这是我的代码,但它还不起作用:

json_dict = {    
    "animal": {"dog": {"type": "beagle"}},
    "man": {"name": "john", "age": 36},
    "plant": {"fruit": {"apple": {"type": "gala"}}}
}

def appendDict(keys, value, json_dict):
    for index, key in enumerate(keys):
        if key not in json_dict:
            if index == len(keys) - 1:
                some_data = {}
                some_data[key] = value
                json_dict[key] = some_data
            else:
                some_data = {}
                json_dict[key] = some_data
        else:
            json_dict[key] = value
            
appendDict(["man", "name"], "daniel", json_dict)            
appendDict(["computer", "laptop", "maker"], "hp", json_dict)

标签: pythonjsondictionary

解决方案


keys您可以通过在每次调用时切片来使用递归:

def appendDict(keys, value, json_dict):
   if len(keys) == 1:
      json_dict[keys[0]] = value
   else:
      if keys[0] not in json_dict:
         json_dict[keys[0]] = {}
      appendDict(keys[1:], value, json_dict[keys[0]])

json_dict = {'animal': {'dog': {'type': 'beagle'}}, 'man': {'name': 'john', 'age': 36}, 'plant': {'fruit': {'apple': {'type': 'gala'}}}}
appendDict(["man", "name"], "daniel", json_dict)
appendDict(["computer", "laptop", "maker"], "hp", json_dict)

import json
print(json.dumps(json_dict, indent=4))

输出:

{
  "animal": {
     "dog": {
        "type": "beagle"
     }
  },
  "man": {
     "name": "daniel",
     "age": 36
   },
   "plant": {
       "fruit": {
          "apple": {
              "type": "gala"
           }
       }
    },
    "computer": {
        "laptop": {
          "maker": "hp"
       }
    }
}

推荐阅读