I have a nested dictionary that looks like below,
{
'product_list.show_date': "May '21",
'product_list.new_users':
{
'product_list.product':
{
'A': None,
'B': 377,
'C': None,
'D': 67,
'E': None,
'F': 1,
'G': None
}
}
}
And I want to clear it out in a way that parent keys are not there. So basically, I want a dictionary that is not nested. Like below,
{
'product_list.show_date': "May '21",
'A': None,
'B': 377,
'C': None,
'D': 67,
'E': None,
'F': 1,
'G': None
}
I am using the recursive function to do this, but it's not 100% correct.
Here's my code,
def clear_nd(d, nested_dict):
for key in nested_dict:
if type(nested_dict[key]) != dict:
d[key] = nested_dict[key]
elif type(nested_dict[key]) == dict:
nested_dict = nested_dict[key]
clear_nd(d, nested_dict)
return d
d = {}
clear_nd(d, nested_dict)
For below example,
nested_dict = {
'product_list.show_date': "May '21",
'product_list.new_users': {
'product_list.product': {
'A': None,
'B': 377,
'C': None,
'D': 67,
'E': None,
'F': 1,
'G': None
},
'prod.product': {
'Alk': None,
'Bay': 377,
'Lent': None,
'R': 67,
'Ter': None,
'Wi': 1,
'e': None
}
},
'duct_list.new_users': {
'pdust.product': {
'H': None,
'y': 377,
'nt': None,
'C': 67,
'sfer': None,
's': 1,
'le': None
}
}
}
Does Pandas
or any other library has a way to do this. Structure of the nested dictionary is dynamic so we won't know how deep it is. And Keys will also change, so we won't able to know beforehand what are the keys in the dictionary. Any help will be appreciated. Thanks!!