0

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

1

1 Answer 1

2

I rewrote the function without recursion.

def to_dict(items):
    res = {}
    for item in items:
        parts = item.split('.')
        dest = res
        for part in parts:
            if not part in dest:
                dest[part] = {}
            dest = dest[part]
    return res

to_dict([
    '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',
])

The alorithm: I split every path into its parts and then build subdicts in a loop keeping a reference dest to the part of dictionary I'm currently in.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I learn programming during the week, and you have helped me greatly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.