Skip to content

Instantly share code, notes, and snippets.

@gt11799
Created December 25, 2015 01:19
Show Gist options
  • Save gt11799/22bcc05b626f82948d93 to your computer and use it in GitHub Desktop.
Save gt11799/22bcc05b626f82948d93 to your computer and use it in GitHub Desktop.
category_iteration
data = [
{
"id": 1,
"parent_id": None,
},
{
"id": 2,
"parent_id": None,
},
{
"id": 3,
"parent_id": 1,
},
{
"id": 4,
"parent_id": 2,
},
{
"id": 5,
"parent_id": 1,
},
{
"id": 6,
"parent_id": 3,
},
{
"id": 7,
"parent_id": 6,
},
{
"id": 8,
"parent_id": 3,
},
]
def the_iter(parent_id, children):
for item in data:
if item['parent_id'] == parent_id:
item['children'] = []
children.append(item)
for item in children:
return the_iter(item['id'], item['children'])
if __name__ == '__main__':
result = []
the_iter(None, result)
print result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment