How to convert a MultiDict to nested dictionary

前端 未结 3 1558
不思量自难忘°
不思量自难忘° 2021-01-04 15:25

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         


        
3条回答
  •  再見小時候
    2021-01-04 16:02

    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

提交回复
热议问题