Reputation: 8124
I have following data:-
data={
"a":{
"b":{
"c":1
},
"f":5
},
"d":"2",
"e":"3",
"g":{
"h":{
"j":"10"
}
}
}
I tried and currently I have following code:-
def myprint(d):
for k, v in d.iteritems():
if isinstance(v, dict):
print "{0}".format(k, v)
myprint(v)
else:
print "{0} : {1}".format(k, v)
myprint(data)
The above code prints following:-
a
b
c : 1
f : 5
e : 3
d : 2
g
h
j : 10
I wanted the output to be following:-
a__b__c = 1
a__f = 5
d = 2
e = 3
g__h__j = 10
Following is the IDE link: https://ideone.com/hWlYUM
Upvotes: 0
Views: 1951
Reputation: 1124968
Pass along a prefix for recursive calls:
def print_nested(d, prefix=''):
for k, v in d.items():
if isinstance(v, dict):
print_nested(v, '{}{}_'.format(prefix, k))
else:
print '{}{} = {}'.format(prefix, k, v)
Demo:
>>> print_nested(data)
a_b_c = 1
a_f = 5
e = 3
d = 2
g_h_j = 10
Upvotes: 4