Created
September 2, 2011 19:16
-
-
Save jcarbaugh/1189566 to your computer and use it in GitHub Desktop.
Create a nested dict from a dotted-key dict
This file contains hidden or 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
def rejigger(src): | |
dst = {} # dict to hold new structure | |
# iterate over keys and values in source dict | |
for key, value in src.iteritems(): | |
set_value(dst, key.split('.'), value) | |
return dst | |
def set_value(d, attrs, value): | |
first_attr = attrs[0] # grab first dotted attribute | |
if len(attrs) == 1: | |
# if only attribute, set it on the dict | |
d[first_attr] = value | |
else: | |
if first_attr not in d: | |
d[first_attr] = {} | |
set_value(d[first_attr], attrs[1:], value) | |
if __name__ == '__main__': | |
data = { | |
'a.b.c': 1, | |
'd': 2, | |
'a.b.x': 3, | |
} | |
print data | |
print rejigger(data) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment