我必须使用不同的嵌套字典,并且我想将字典 A 中的一些键替换为字典 B 中的相应值 这是字典 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"
}
]
}
]
}
]
}
最佳答案
您需要先创建一个新条目,然后删除旧条目。 Change the name of a key in dictionary
关于python - 如何替换嵌套字典中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56132513/