def add_to_list(new_item, parent_list): if new_item["type"] == "header": #create a new list and call add_to_list with that? else if: new_item["type"] == "footer": #close the list and jump back? else: parent_list.append(new_item) test_data = [{"id":1, "type":"blurb", "info":"This is the blurb"}, {"id":2, "type":"header", "info":"This is the first group header"}, {"id":3, "type":"question", "info":"This is the first question"}, {"id":4, "type":"question", "info":"This is the second question"}, {"id":5, "type":"header", "info":"This is the second group header"}, {"id":6, "type":"question", "info":"This is the third question"}, {"id":7, "type":"question", "info":"This is the fourth question"}, {"id":8, "type":"footer", "info":"This is the footer for the second header"}, {"id":9, "type":"question", "info":"This is the fifth question"}, {"id":10, "type":"footer", "info":"This is the footer for the first header"}] nested_data = [] for item in test_data: add_to_list(item, nested_data) print nested_data
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question