Skip to content

Instantly share code, notes, and snippets.

@astanway
Last active December 10, 2015 01:18
Show Gist options
  • Save astanway/4356787 to your computer and use it in GitHub Desktop.
Save astanway/4356787 to your computer and use it in GitHub Desktop.
Wherein a drunk Abe needed a fast and easy way to turn a namespaced string into a nested dictionary.
string = "stats.pages.home_page.visitors"
split_string = string.split('.')
tree = {}
tree_string = 'tree'
for i in range(0, len(split_string)):
try:
tree_string = tree_string + '[split_string[' + str(i) + ']]'
exec(tree_string)
except KeyError:
if i + 1 == len(split_string):
set_tree = tree_string + " = 1"
else:
set_tree = tree_string + " = {}"
exec(set_tree)
print tree
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment