Skip to content

Instantly share code, notes, and snippets.

@DivineGod
Last active December 23, 2015 23:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DivineGod/6713282 to your computer and use it in GitHub Desktop.
Save DivineGod/6713282 to your computer and use it in GitHub Desktop.
Convert a flat dict into an object
def kwargs_to_obj(**kwargs):
""" Return an object populated from a kwargs dict.
Useful for mapping html form post request to python object.
>>> kwargs_to_obj(**{'horse.age':23, 'horse.color': 'bleu', 'horse.legs[]': 'fl,fr,rl,rr'})
{'horse': {'color': 'bleu', 'age': 23, 'legs': ['fl', 'fr', 'rl', 'rr']}}
"""
result = {}
for k, v in kwargs.items():
name_path = k.split('.')
np = name_path.pop(0)
temp = result.get(np, {})
result[np] = temp
res_temp = {}
depth = 0
for np in name_path:
depth += 1
if '[]' in np:
np = np.replace('[]', '')
temp[np] = temp.get(np, [])
v = v.split(',')
else:
temp[np] = temp.get(np, {})
res_temp = temp
temp = temp[np]
if depth == 0:
result[np] = v
else:
res_temp[np] = v
return result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment