Created
February 5, 2020 13:21
-
-
Save AvinashDalvi89/8bc8677b00bd4b79e701ad08b503a1a8 to your computer and use it in GitHub Desktop.
This is to convert list of dictionary which will have child- parent relation to each other. This will convert to nested hierarchy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
data = [ | |
{ "name" : "ABC", "parent":"DEF", }, | |
{ "name" : "DEF", "parent":"null" }, | |
{ "name" : "new_name", "parent":"ABC" }, | |
{ "name" : "new_name2", "parent":"ABC" }, | |
{ "name" : "Foo", "parent":"DEF"}, | |
{ "name" : "Bar", "parent":"null"}, | |
{ "name" : "Chandani", "parent":"new_name", "relation": "rel", "depth": 3 }, | |
{ "name" : "Chandani333", "parent":"new_name", "relation": "rel", "depth": 3 } | |
] | |
result = {x.get("name"):x for x in data} | |
#print(result) | |
tree = []; | |
for a in data: | |
#print(a) | |
if a.get("parent") in result: | |
parent = result[a.get("parent")] | |
else: | |
parent = "" | |
if parent: | |
if "children" not in parent: | |
parent["children"] = [] | |
parent["children"].append(a) | |
else: | |
tree.append(a) | |
print(tree) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment