I would like to print nested hash in Python, from this:
example_dict = {
'key1' : 'value1',
'key2' : {
'key2a': 'value2a'
},
'key3' : {
'key3a': {
'key3aa': 'value3aa',
'key3ab': 'value3ab',
'key3ac': 'value3ac'
},
'key3b': [
'value3b1',
'value3b2'
]
},
}
to something like this:
key1 value1
key2 key2a value2a
key3 key3a key3aa value3aa
key3 key3a key3ab value3ab
key3 key3a key3ac value3ac
key3 key3b value3b1
key3 key3b value3b2
I am not really familiar with Python, and after couple hours I'm still stuck.
I currently working on this function:
def recursive(src, res, line = ''):
if isinstance(src, dict):
for key, value in src.items():
line += str(' ' + key)
recursive(value, res, line)
elif isinstance(src, list):
for litem in src:
recursive(litem, res, line)
else:
line += str(' ' + str(src))
res.append(line)
I'm trying to add each line to a list to be able to use it later, but I think I don't have the right aproach with my shared variable (line), because at each dict the recursive call is made with one more dict key from the same level of depth, so I got this :
key3 key3a key3aa value3aa
key3 key3a key3aa key3ac value3ac
key3 key3a key3aa key3ac key3ab value3ab
key3 key3a key3b value3b1
key3 key3a key3b value3b2
key3 key2 key2a value2a
key3 key2 key1 value1
What would be a Pythonic way to do this?