如何在嵌套字典中替换值

时间:2019-05-14 14:14:02

标签: python python-3.x

我必须使用不同的嵌套字典,我想用字典B中的相应值替换字典A中的某些键 这是字典A

{
  "Animals": {
    "catgry": {
      "1": "Dogs",
      "2": "Cats",
      "3": "Birds",
    }
  },
  "dogBreeds": {
    "catgry": {
      "1": "Belgian Malinois",
      "2": "Australian Bulledog",
      "3": "Cane Corso",
      "4": "Chow chow",
      "5": "Dalmatian",
      "6": "Dobermann",
      "7": "Labrador",
      "8": "Rottweiler"
    }
  }
}

字典B是

{
  "name": "MyGarden",
  "children": [
    {
      "name": "Animals",
      "Animals":"1",
      "children": [
        {
          "name": "dogBreeds",
          "dogBreeds":"1",
          "children": [
            {
              "name": "myBelgian malinois",
              "weight": "30"
            }
          ]
        },
        {
          "name": "dogBreeds",
          "dogBreeds":"2",
          "children": [
            {
              "name": "myAustralian Bulledog",
              "weight": "35"
            }
          ]
        }
      ]
    }
  ]
}

我首先尝试从字典A中删除键“ catgry”,然后将值替换为对应的键,但是没有删除子级也没有成功

[编辑] 这是预期的结果

{
  "name": "MyGarden",
  "children": [
    {
      "Animals":"Dogs",
      "children": [
        {
          "dogBreeds":"Belgian Malinois",
          "children": [
            {
              "name": "myBelgian malinois",
              "weight": "30"
            }
          ]
        },
        {
          "dogBreeds":"Australian Bulledog",
          "children": [
            {
              "name": "myAustralian Bulledog",
              "weight": "35"
            }
          ]
        }
      ]
    }
  ]
}

3 个答案:

答案 0 :(得分:1)

您需要先创建一个新条目,然后删除旧条目。 Change the name of a key in dictionary

答案 1 :(得分:0)

因此,我在这里对嵌套字典将包含的类型以及catgry下标的存在做出一些假设。

但是,您应该可以通过递归解决此问题。

def val_replace(dictb, refdict):
    for k, v in dictb.items():
        if k in refdict:
            dictb[k] = refdict[k]['catgry'][v]
        elif isinstance(v, dict):
            val_replace(v, refdict)
        elif isinstance(v, list):
            for v2 in v:
                if isinstance(v2, dict):
                    val_replace(v2, refdict)

myref = {
  "Animals": {
    "catgry": {
      "1": "Dogs",
      "2": "Cats",
      "3": "Birds",
    }
  },
  "dogBreeds": {
    "catgry": {
      "1": "Belgian Malinois",
      "2": "Australian Bulledog",
      "3": "Cane Corso",
      "4": "Chow chow",
      "5": "Dalmatian",
      "6": "Dobermann",
      "7": "Labrador",
      "8": "Rottweiler"
    }
  }
}

mydict = {
  "name": "MyGarden",
  "children": [
    {
      "name": "Animals",
      "Animals":"1",
      "children": [
        {
          "name": "dogBreeds",
          "dogBreeds":"1",
          "children": [
            {
              "name": "myBelgian malinois",
              "weight": "30"
            }
          ]
        },
        {
          "name": "dogBreeds",
          "dogBreeds":"2",
          "children": [
            {
              "name": "myAustralian Bulledog",
              "weight": "35"
            }
          ]
        }
      ]
    }
  ]
}

val_replace(mydict, myref)

结果是:

{
    'name': 'MyGarden', 
    'children': [
        {
         'name': 'Animals', 
         'Animals': 'Dogs', 
         'children': [
             {
              'name': 'dogBreeds', 
              'dogBreeds': 'Belgian Malinois', 
              'children': [
                  {'name': 'myBelgian malinois', 'weight': '30'}
              ]
             }, 
            {
             'name': 'dogBreeds', 
             'dogBreeds': 'Australian Bulledog', 
             'children': [
                  {'name': 'myAustralian Bulledog', 'weight': '35'}
             ]
            }
          ]
         }
     ]
}

答案 2 :(得分:0)

您可以使用递归:

a = {'Animals': {'catgry': {'1': 'Dogs', '2': 'Cats', '3': 'Birds'}}, 'dogBreeds': {'catgry': {'1': 'Belgian Malinois', '2': 'Australian Bulledog', '3': 'Cane Corso', '4': 'Chow chow', '5': 'Dalmatian', '6': 'Dobermann', '7': 'Labrador', '8': 'Rottweiler'}}}
b = {'name': 'MyGarden', 'children': [{'name': 'Animals', 'Animals': '1', 'children': [{'name': 'dogBreeds', 'dogBreeds': '1', 'children': [{'name': 'myBelgian malinois', 'weight': '30'}]}, {'name': 'dogBreeds', 'dogBreeds': '2', 'children': [{'name': 'myAustralian Bulledog', 'weight': '35'}]}]}]}
def rename(d):
  return {**d, 'children':list(map(rename, d.get('children', [])))} if d['name'] not in a else \
      {d['name']:a[d['name']]['catgry'][d[d['name']]], 'children':list(map(rename, d.get('children', [])))}

输出:

{
  "name": "MyGarden",
  "children": [
    {
        "Animals": "Dogs",
        "children": [
            {
                "dogBreeds": "Belgian Malinois",
                "children": [
                    {
                        "name": "myBelgian malinois",
                        "weight": "30",
                        "children": []
                    }
                ]
            },
            {
                "dogBreeds": "Australian Bulledog",
                "children": [
                    {
                        "name": "myAustralian Bulledog",
                        "weight": "35",
                        "children": []
                    }
                ]
            }
        ]
      }
   ]
}