Thursday, 15 August 2013

Walk recursively through childs of a list in Python

Walk recursively through childs of a list in Python

I try to recursively print sentences from a nested list of lists
I want to obtain a list containing
['big bad dog', 'big fluffy cat', 'small blue happy pony', 'small frog']
Here is my code, it don't work...
Am I on the right path or I should structure my data in an another way to
achieve my goal?
from pprint import pprint
dirs = [
{
'kw': 'big',
'childs': [
{
'kw': 'bad',
'childs': [
{
'kw': 'dog'
}
]
},
{
'kw': 'fluffy',
'childs': [
{
'kw': 'cat'
}
]
}
]
},
{
'kw': 'small',
'childs': [
{
'kw': 'blue',
'childs': [
{
'kw': 'happy',
'childs': [
{
'kw': 'pony'
}
]
}
]
},
{
'kw': 'frog'
}
]
},
]
def traverse(d, l):
kw = d.get('kw')
c = d.get('childs')
l.append(kw)
if c:
for cc in c:
l = traverse(cc, l)
return l
r = traverse(dirs[0], [])
pprint(r)

No comments:

Post a Comment