替换字典或嵌套字典或字典列表中键值的泛型函数 [英] Generic Function to replace value of a key in a dict or nested dict or list of dicts
问题描述
所以我有一个像这样的词典:
So i have a Dict like so:
{
"environment": [
{
"appliances": [
{
"services-status": "GOOD",
"ping-status": "REACHABLE"
},
{
"softwareVersion": "16.1-R1-S2 50b46b5 20170829",
"services-status": "GOOD",
"ping-status": "REACHABLE"
}
],
"vd_url": "https://bla1"
},
{
"appliances": [
{
"ipAddress": "10.4.64.108"
"type": "branch",
"sync-status": "IN_SYNC"
},
{
"services-status": "GOOD",
"ping-status": "REACHABLE"
"sync-status": "IN_SYNC"
}
],
"vd_url": "https://bla2"
},
],
"failed_urls": [
"https://gslburl",
"https://gslburl",
"https://localhost",
"https://localhost",
"https://localhost"
]
}
或者可以是这样的
{
"softwareVersion": "16.1-R1-S2 50b46b5 20170829",
"services-status": "GOOD",
"ping-status": "REACHABLE"
"vd_url" : "https://blah3"
}
或者可以是这样的
{
"environment": [
{
"appliances": [
{
"services-status": "GOOD",
"ping-status": "REACHABLE"
},
{
"softwareVersion": "16.1-R1-S2 50b46b5 20170829",
"services-status": "GOOD",
"ping-status": "REACHABLE"
}
],
"vd_url": "https://bla1"
}
]
}
或者它可以是字典的任意组合,但是我要实现的目标是编写一个可以接受字典的泛型函数, 将键替换为另一个值并返回新字典. 只是一个伪代码:
or it can be in any combination of dictionaries possible, but what i am trying to achieve is write a generic function that can take the dictionary, replace a key with another value and return the new dict. Just a pseudo code:
def replace(dict_obj, key, new_value)
for dict in dict_obj:
for k, v in dict.items()
if k == key:
dict[k] = new_value
return dict_obj
但是最后,我希望使用相同的字典对象-传递的dict_obj,但是具有新值,它应该适用于上述任何类型的dict 如何解决它to不休:(
but in the end i want the same dictionary object - dict_obj that i passed but with the new values and it should work for any type of dicts above Scratching my head as to how to solve it :(
推荐答案
您可以使用递归来确定键,值对中的值是列表还是dict,然后进行相应的迭代.
You can use recursion to determine if value from a key,value pair is a list or a dict and then iterate accordingly.
def replace(dict_obj, key, new_value):
for k,v in dict_obj.iteritems():
if isinstance(v,dict):
# replace key in dict
replace(v, key, new_value)
if isinstance(v,list):
# iterate through list
for item in v:
if isinstance(item,dict):
replace(item, key, new_value)
if k == key:
dict_obj[k] = new_value
这篇关于替换字典或嵌套字典或字典列表中键值的泛型函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!