Created
January 9, 2018 15:47
-
-
Save diraol/e4ffb26b433be6aafd33b383308edf6e to your computer and use it in GitHub Desktop.
Create a nested python dict from a list of items to be splitted
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
# This gist shows how to build a nested python dict | |
# based on a string that will be splitted based on one specific character | |
# It can be a list, a dict or whatever you want to. | |
one_level_dict = { | |
'2.0/jobs/create': 'POST', | |
'2.0/jobs/list': 'GET', | |
'2.0/jobs/delete': 'POST', | |
'2.0/jobs/get': 'GET', | |
'2.0/jobs/reset': 'POST', | |
'2.0/jobs/run-now': 'POST', | |
'2.0/jobs/runs/submit': 'POST', | |
'2.0/jobs/runs/list': 'GET', | |
'2.0/jobs/runs/get': 'GET', | |
'2.0/jobs/runs/export': 'GET', | |
'2.0/jobs/runs/cancel': 'POST', | |
'2.0/jobs/runs/get-output': 'GET' | |
} | |
nested_dict = {} | |
# Splitting the endpoint path into a dict tree | |
for path, method in one_level_dict.items(): | |
parts = path.split("/") | |
current_node = nested_dict | |
for part in parts[:-1]: | |
if part not in current_node: | |
current_node[part] = {} | |
current_node = current_node[part] | |
if parts[-1] not in current_node: | |
current_node[parts[-1]] = method | |
# Expected output: | |
{'2.0': {'jobs': {'create': 'POST', | |
'delete': 'POST', | |
'get': 'GET', | |
'list': 'GET', | |
'reset': 'POST', | |
'run-now': 'POST', | |
'runs': {'cancel': 'POST', | |
'export': 'GET', | |
'get': 'GET', | |
'get-output': 'GET', | |
'list': 'GET', | |
'submit': 'POST'}}}} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment