修改的是字典中的key值.这个只能修改key值.
借鉴代码 点击跳转 借鉴的代码是修改的value
数据源
{
"code": 200,
"data": {
"_id": "fa69c4a650b9454a22ab13c781ede848",
"org_name": "7",
"p_id": "a34b95fa8d2b491b1cd91b122ab7a92b",
"org_id": "ca93ed9207956708a4dad3e8f1ac3b52",
"create_time": 1649238531,
"update_time": 1649238531,
"sons": [
{
"_id": "912872c3548a75c505de3dfd60288902",
"org_name": "7",
"p_id": "ca93ed9207956708a4dad3e8f1ac3b52",
"org_id": "ac5b45ffe0a17239809282ef714d77f6",
"create_time": 1649239187,
"update_time": 1649239187,
"sons": [
]
}
]
},
"msg": "success"
}
代码
def update(key, dict_data, modify):
if key in dict_data:
dict_data[modify] = dict_data.pop(key)
for keys, values in dict_data.items():
if isinstance(values, (list, tuple)):
for i in values:
if key in i and isinstance(i, dict):
update(key, i, modify)
else:
get_value(i, key, modify)
elif isinstance(values, dict):
if key in values:
update(key, values, modify)
else:
for keys, values in values.items():
if isinstance(values, dict):
update(key, values, modify)
else:
for keys, values in dict_data.items():
if isinstance(values, (list, tuple)):
for i in values:
if key in i:
update(key, i, modify)
else:
get_value(i, key, modify)
elif isinstance(values, dict):
if key in values:
update(key, values, modify)
else:
get_value(values, key, modify)
return dict_data
def get_value(tt, key, modify):
for values in tt.values():
if isinstance(values, (list, tuple)):
for i in values:
if key in i and isinstance(i, dict):
update(key, i, modify)
else:
get_value(i, key, modify)
elif isinstance(values, dict):
if key in values:
update(key, values, modify)
else:
get_value(values, key, modify)
list_item = [
{"initial": "_id", "modify": "t_id"},
{"initial": "p_id", "modify": "pp_id"},
{"initial": "code", "modify": "status_code"},
]
def get_end_dict(list_x: list):
for num, value in enumerate(list_x):
update(key=value['initial'], dict_data=data, modify=value['modify'])
if num + 1 == len(list_item):
return update(key=value['initial'], dict_data=data, modify=value['modify'])
print(get_end_dict(list_item))
数据结果
{
"data": {
"org_name": "7",
"org_id": "ca93ed9207956708a4dad3e8f1ac3b52",
"create_time": 1649238531,
"update_time": 1649238531,
"sons": [
{
"org_name": "7",
"org_id": "ac5b45ffe0a17239809282ef714d77f6",
"create_time": 1649239187,
"update_time": 1649239187,
"sons": [],
"t_id": "912872c3548a75c505de3dfd60288902",
"pp_id": "ca93ed9207956708a4dad3e8f1ac3b52"
}
],
"t_id": "fa69c4a650b9454a22ab13c781ede848",
"pp_id": "a34b95fa8d2b491b1cd91b122ab7a92b"
},
"msg": "success",
"status_code": 200
}
|