Last active
December 23, 2015 23:59
-
-
Save DivineGod/6713282 to your computer and use it in GitHub Desktop.
Convert a flat dict into an object
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 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