1

I had a problem on converting dictionaries to strings which has recursive features. I had a map of routing such as the following;

urls = {
    '/' : 'BaseController.hello',
    '/api' : {
        '/auth' : {
            '/me' : 'ApiController.hello',
            '/login' : {
                '/guest' : 'ApiController.guest_login',
                '/member': 'ApiController.member_login'
            }
        }
    }
}

What I need to do is to generate a dictionary from that into the following;

url_map = {
    '/' : 'BaseController.hello',
    '/api/auth/me' : 'ApiController.hello',
    '/api/auth/login/guest' : 'ApiController.guest_login',
    '/api/auth/login/member': 'ApiController.member_login',
}

This feature is called route grouping but I haven't been able to write a function to generate that. Any ideas ?

1
  • I haven't been able to write a function,- show your attempts then. Commented Jul 23, 2014 at 13:19

1 Answer 1

4

You can recursively do it like this

def flatten(current_dict, current_key, result_dict):

    # For every key in the dictionary
    for key in current_dict:
        # If the value is of type `dict`, then recurse with the value
        if isinstance(current_dict[key], dict):
            flatten(current_dict[key], current_key + key, result_dict)
        # Otherwise, add the element to the result
        else:
            result_dict[current_key + key] = current_dict[key]
    return result_dict

print flatten(urls, "", {})

Output

{
    '/api/auth/me': 'ApiController.hello',
    '/api/auth/login/guest': 'ApiController.guest_login',
    '/': 'BaseController.hello',
    '/api/auth/login/member': 'ApiController.member_login'
}
Sign up to request clarification or add additional context in comments.

2 Comments

I would have thought that you would have to pass result_dict in the recursive call - does this work because dict is a mutable default argument?
@wwii It works because the default parameters are evaluated only when the function is defined, not when it is invoked.

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.