I have a list of paths that need to be converted to a dict
[
"/company/accounts/account1/accountId=11111",
"/company/accounts/account1/accountName=testacc",
"/company/accounts/account1/environment=test",
"/company/accounts/account2/accountId=22222",
"/company/accounts/account2/accountName=stageacc",
"/company/accounts/account2/environment=stage",
"/program/releases/program1/stage/version=1.1",
"/program/releases/program1/stage/date=2021-02-01",
"/program/releases/program1/prod/version=1.0",
"/program/releases/program1/prod/date=2021-01-15",
]
Here is what it should look like:
{
"company": {
"accounts": {
"account1": {
"accountId": 11111,
"accountName": "testacc",
"environment": "test"
},
"account2": {
"accountId": 22222,
"accountName": "stageacc",
"environment": "stage"
}
}
},
"program": {
"releases": {
"program1": {
"stage": {
"version": "1.1",
"date": "2021-02-01"
},
"prod": {
"version": "1.0",
"date": "2021-01-15"
}
}
}
}
}
I am trying to solve this iteratively but I can't seem to get it to work. Not sure what is the right approach here when it comes to nested dictionaries.
Here is my code:
class Deserialize:
def __init__(self):
self.obj = {}
def deserialize_iteratively(self, paths):
def helper(path):
path_elements = path.split('/')
for e in path_elements[::-1]:
if "=" in e:
k,v = e.split("=")
self.obj[k] = v
else:
tmp = {}
tmp[e] = self.obj
self.obj = tmp
return self.obj
for path in paths:
helper(path)
return self.obj
And the erroneous output this generates with first two paths:
{'': {'company': {'accounts': {'account1': {'': {'company': {'accounts': {'account1': {'accountId': '11111'}}}},
'accountName': 'testacc'}}}}}