I have a complicated json file coming from somewhere and I am trying to get n level dictionary and discard the rest. (so this is not flattening as such). For example given a dict of countries and their subcountries and cities
my_dict = {
'USA':['California', 'Arizona', {'Ohio':'Columbus'}],
'Zimbabwe':{'Manicaland':['Mutare', 'Nyanga']},
'New Zealand':''
}
Calling for level 1 to get list of countries
n_level(my_dict, 1)
Should give
['USA', 'Zimbabwe', 'New Zealand']
#calling for level 2
n_level(my_dict, 2)
#should give
[
{'USA':['California', 'Arizona', 'Ohio']},
{'Zimbabwe':'Manicaland'}, #<--str
'New Zealand'
]
I have tried this but not working no idea
my_dict = {
'USA':['California', 'Arizona', {'Ohio':'Columbus'}],
'Zimbabwe':{'Manicaland':['Mutare', 'Nyanga']}
}
def make_leaf_list(d):
r = []
if isinstance(d, collections.abc.Mapping):
for k, v in d.items():
r.append(k)
elif isinstance(d, list):
for i in d:
r.extend(make_leaf_list(i))
else:
return r.append(d)
return r
def n_level(o, depth):
if depth == 0:
return make_leaf_list(o)
if isinstance(o, collections.abc.Mapping):
r = {}
for k, v in o.items():
r[k] = n_level(v, depth-1)
return r
elif isinstance(o, list):
r = []
for i in o:
r.append(update(i, depth-1))
return r
else:
return o
#and calling it
n_level(my_dict, 3)
Any idea for the approach? Thanks