I have the following code that tries to cover most cases of a dictionary walk, and output it as indented text (indent based on the items’ nesting in the dictionary. There are two problems:
- I think the check at the start, which caters for "raw_list", is a bit of a hack, but I cannot think of a better way
- I cannot get the level variable to properly reflect its position
Thanks. I think the rest of the recursion is correct…
a = {
"raw_list" : [1,2,3],
"a" : 1,
"b" : 2,
"mydict": {
"c":3,
"d":4
},
"mydict2": {
"c":5,
"d":6
},
"list1": [
{
"e1":7,
"e2":8
},
{
"e3":9,
"e4":10
}
],
"list2": [
{
"f1":11,
"f2":12
}
]
}
def process_data(data,level):
if not isinstance(data,list) and not isinstance(data,dict) :
print("\t"*level + str(data))
return
for element, val in data.items():
if isinstance(val, dict):
print("\t"*level + "DICT:" + element)
level+=1
process_data(val,level)
elif isinstance(val, list):
print("\t"*level + "LIST:" + element)
level += 1
for i, item in enumerate(val):
process_data(item,level)
else:
print("\t"*level+element + ":" + str(val))
level-=1
process_data(a,1)
Got this:
LIST:test
1
2
3
a:1
b:2
DICT:mydict
c:3
d:4
DICT:mydict2
c:5
d:6
LIST:list1
e1:7
e2:8
e3:9
e4:10
LIST:list2
f1:11
f2:12
But want this:
LIST:test
1
2
3
a:1
b:2
DICT:mydict
c:3
d:4
DICT:mydict2
c:5
d:6
LIST:list1
e1:7
e2:8
e3:9
e4:10
LIST:list2
f1:11
f2:12
>Solution :
You are incrementing the level for each element in a loop. Instead, try removing level += 1 and pass incremented level into the recursive call: process_data(item, level + 1).