a={
"a": "1",
"b": "2",
"c": "3",
"properties": {
"test1": "1",
"test2": "2",
"test3": {
"a1": "70",
"a2": "71",
"a3": {
"b1": "80",
"b2": "81",
"properties": {
"b1": "20",
"b2": "21",
},
"d1": "30",
"d2": "31",
},
},
},
}
i want "a" to just have all the keys and value inside of "properties" key.
final_a = {
"test1": "1",
"test2": "2",
"test3": {
"a1": "70",
"a2": "71",
"a3": {
"b1": "20",
"b2": "21",
},
},
}
I have tried all the solution on Find all occurrences of a key in nested dictionaries and lists
CodePudding user response:
IIUC, you can use a recursive function. If properties is a key, replace the current iteration with it else return the dictionary applying the function on the dictionary values:
def nested_prop(d):
if 'properties' in d:
return nested_prop(d['properties'])
return {k:nested_prop(v) if isinstance(v, dict) else v
for k,v in d.items()}
nested_prop(a)
output:
{'test1': '1',
'test2': '2',
'test3': {'a1': '70', 'a2': '71', 'a3': {'b1': '20', 'b2': '21'}}}
CodePudding user response:
You could use a recursive update function to traverse through a dict and search for any properties
key, as shown below:
from pprint import pprint
a = {
"a": "1",
"b": "2",
"c": "3",
"properties": {
"test1": "1",
"test2": "2",
"test3": {
"a1": "70",
"a2": "71",
"a3": {
"b1": "80",
"b2": "81",
"properties": {
"b1": "20",
"b2": "21",
},
"d1": "30",
"d2": "31",
},
},
},
}
def recursive_update(d: dict) -> dict:
if 'properties' in d:
d = d['properties']
for k, v in d.items():
if isinstance(v, dict):
d[k] = recursive_update(v)
elif isinstance(v, list):
d[k] = [recursive_update(e) if isinstance(e, dict) else e for e in v]
return d
print('Before:')
print(a)
# {'a': '1', 'b': '2', 'c': '3', 'properties': {'test1': '1', 'test2': '2', 'test3': {'a1': '70', 'a2': '71', 'a3': {'b1': '80', 'b2': '81', 'properties': {'b1': '20', 'b2': '21'}, 'd1': '30', 'd2': '31'}}}}
a = recursive_update(a)
print('After:')
pprint(a)
Result:
Before:
{'a': '1', 'b': '2', 'c': '3', 'properties': {'test1': '1', 'test2': '2', 'test3': {'a1': '70', 'a2': '71', 'a3': {'b1': '80', 'b2': '81', 'properties': {'b1': '20', 'b2': '21'}, 'd1': '30', 'd2': '31'}}}}
After:
{'test1': '1',
'test2': '2',
'test3': {'a1': '70', 'a2': '71', 'a3': {'b1': '20', 'b2': '21'}}}