Skip to content

Instantly share code, notes, and snippets.

@jcarbaugh
Created September 2, 2011 19:16
Show Gist options
  • Save jcarbaugh/1189566 to your computer and use it in GitHub Desktop.
Save jcarbaugh/1189566 to your computer and use it in GitHub Desktop.
Create a nested dict from a dotted-key dict
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