I have the following code, which must convert this tuple
(
'person.firstname',
'person.patronymic',
'person.documents.type',
'person.documents.number',
'person.employee_set.unit.short_name',
'person.employee_set.group_set.name',
'person.employee_set.group_set.period.code',
'unit.short_name',
)
to dictionary like this
{
"person": {
"patronymic": {},
"documents": {
"type": {},
"number": {}
},
"employee_set": {
"unit": {
"short_name": {}
},
"group_set": {
"name": {},
"period": {
"code": {}
}
}
},
"firstname": {}
},
"unit": {
"short_name": {}
}
}
code:
def to_dict(items):
di = {}
for item in items:
parse(di, item)
return di
def parse(di, item):
sep = item.find('.')
if sep != -1:
key = item[:sep]
if not key in di.keys():
di[key] = {}
return parse(di[key], item[sep + 1:])
elif len(item) > 0:
di[item] = {}
return di
It is possible to optimize this code without recursion? As I understand it there tail recursion, but I do not understand how to transform it in a loop