Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 367
Kyle Finley Avatar asked Jan 30 '12 00:01

Kyle Finley


People also ask

How do you make nested dictionaries?

Creating a Nested Dictionary In Python, a Nested dictionary can be created by placing the comma-separated dictionaries enclosed within braces.

How do you make a list into a dictionary?

To convert a list to dictionary, we can use list comprehension and make a key:value pair of consecutive elements. Finally, typecase the list to dict type.

What is a nested dictionary explain with an example?

In Python, a nested dictionary is a dictionary inside a dictionary. It's a collection of dictionaries into one single dictionary.

Can dictionary be nested to any depth?

Dictionaries can be nested to any depth. All the keys in a dictionary must be of the same type. Dictionaries are accessed by key.


2 Answers

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

like image 72
Will Avatar answered Oct 23 '22 21:10

Will


I haven't had the time to test it and it's quite restrictive, but hopefully this will work (I'm only posting because it's been a while since you posted the question):

>>> def toList(s):
...     answer = []
...     L = s.split("&")
...     for i in L:
...             answer.append(tuple(i.split('=')))
...     return answer

>>> def toDict(L):
...     answer = {}
...     answer[L[0][0]] = L[0][1]
...     for i in L[1:]:
...             pk,sk = L[i][0].split('.')
...             if pk not in answer:
...                     answer[pk] = []
...             if sk not in answer[pk][-1]:
...                     answer[pk][sk] = L[i][1]
...             else:
...                     answer[pk].append({sk:L[i][1]})

If this is not 100%, it should at least get you on a good start.

Hope this helps

like image 1
inspectorG4dget Avatar answered Oct 23 '22 21:10

inspectorG4dget