Skip to content

Instantly share code, notes, and snippets.

@sandromello
Created June 20, 2015 16:02
Show Gist options
  • Save sandromello/f3e0f7fe7e5884b44259 to your computer and use it in GitHub Desktop.
Save sandromello/f3e0f7fe7e5884b44259 to your computer and use it in GitHub Desktop.
recursiveness - parent_ids
data = [{
'id' : 1,
'title' : 'root',
'parent_id' : 'DRIVE',
'isroot' : True,
'abs_path' : 'root'
},
{
'id' : 2,
'parent_id' : 'DRIVE',
'title' : 'root2',
'isroot' : True,
'abs_path' : 'root2'
},
{
'id' : 3,
'parent_id' : 2,
'title' : '2nd-root2',
'isroot' : False,
'abs_path' : ''
},
{
'id' : 4,
'parent_id' : 3,
'title' : '3rd-root2',
'isroot' : False,
'abs_path' : ''
},
{
'id' : 5,
'parent_id' : 1,
'title' : '2nd-root',
'isroot' : False,
'abs_path' : ''
},
{
'id' : 6,
'parent_id' : 1,
'title' : '2nd-2-root',
'isroot' : False,
'abs_path' : ''
},
{
'id' : 7,
'parent_id' : 6,
'title' : '3rd-2-root',
'isroot' : False,
'abs_path' : ''
},
{
'id' : 8,
'parent_id' : 7,
'title' : '4rd-2-root',
'isroot' : False,
'abs_path' : ''
},
]
def discover(root, data):
if not root:
for d in data:
if d['isroot']:
discover(d, data)
else:
for d in data:
if root['id'] == d['parent_id']:
if not d['abs_path']:
if root['isroot']:
d['abs_path'] += '%s/%s' % (root['title'], d['title'])
else:
d['abs_path'] += '%s/%s' % (root['abs_path'], d['title'])
discover(d, data)
discover(None, data)
for d in data:
print d['title'], d['abs_path']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment