I would like to convert a POST from Webob MultiDict to nested dictionary. E.g.
So from a POST of:
\'name=Kyle&phone.number=1234&phone.type=ho
I prefer an explicit way to solve your problem:
Divide the members which belong to the same structure (or dict) into a same group with same field name, like
'name=Kyle&phone1=1234&phone1=home&phone2=5678&phone2=work'
The order of the fields in the form is guaranteed, so the multidict will be: (('name', 'Kyle'), ('phone1', '1234', 'home'), ('phone2', '5678', 'work'))
Then the code will be like:
def extract(key, values):
extractor = {
"name":str,
"phone":lambda *args:dict(zip(('number', 'type'), args)
}
trimed_key = re.match(r"^(\w+)", key).group(1)
return trimed_key, extractor(trimed_key, *values)
nested_dict = {}
for i in multidict():
key, values = i[0], i[1:]
nested_dict.setdefault(key, [])
trimed_key, data_wanted = extract(key, values)
nested_dict[trimed_key].append(data_wanted)
for key in nested_dict:
if len(nested_dict[key]) == 1:
nested_dict[key] = nested_dict[key][0]