If below is my nested dictionary I want to parse through recursively and print all the values along with the complete path of the nested key.
my_dict = {'attr':{'types':{'tag':{'name':'Tom', 'gender':'male'},'category':'employee'}}}
Expected output:
Key structure : my_dict["attr"]["types"]["tag"]["name"]<br>
value : "Tom"<br>
Key structure : my_dict["attr"]["types"]["tag"]["gender"]<br>
value : "male"<br>
Key structure : my_dict["attr"]["types"]["category"]<br>
value : "employee"<br>
I wrote a recursive function, but running to this:
my_dict = {'attr':{'types':{'tag':{'name':'Tom','gender':'male'},'category':'employee'}}}
def dict_path(path,my_dict):
for k,v in my_dict.iteritems():
if isinstance(v,dict):
path=path+"_"+k
dict_path(path,v)
else:
path=path+"_"+k
print path,"=>",v
return
dict_path("",my_dict)
Output:
_attr_types_category => employee
_attr_types_category_tag_gender => male
_attr_types_category_tag_gender_name => Tom
In the above : For male, the key struct shouldnt contain "category" How to retain the correct key structure?