Search code examples
pythonnestednested-formswebob

How to convert a MultiDict to nested dictionary


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=home&phone.number=5678&phone.type=work'

to a multidict;

[('name', 'Kyle'), ('phone.number', '1234'), ('phone.type', 'home'), ('phone.number', '5678'), ('phone.type', 'work')]

to a nested dictionary

{'name': 'Kyle',
 'phone': [
  {
    'number': '12345',
    'type': 'home',
  },{
    'number': '5678',
    'type': 'work',
  },

Any ideas?

EDIT

I ended up extracting the variable_decode method from the formencode package as posted by Will. The only change that was required is to make the lists explicit, E.g.

'name=Kyle&phone-1.number=1234&phone-1.type=home&phone-2.number=5678&phone-2.type=work'

Which is better for many reasons.


Solution

  • If you have formencode installed or can install it, checkout out their variabledecode module