Django, Python: Is There A Simple Way To Convert Php-style Bracketed Post Keys To Multidimensional Dict?
Solution 1:
I made a little parser in python to handle multidimensional dicts, you can find it at https://github.com/bernii/querystring-parser
Solution 2:
Dottedish does something like what you want. http://pypi.python.org/pypi/dottedish. It doesn't really have a homepage but you can install it from pypi or download the source from github.
>>> import dottedish
>>> dottedish.unflatten([('3.name', 'a'), ('3.spec', 'b')])
{'3': {'name': 'a', 'spec': 'b'}}
Solution 3:
I am riding off of the previous response by Atli about using PHP's json_encode
...
A Python dict in its most basic form is syntactically identical to JSON. You could easily perform an eval()
on a JSON structure to create a Python dict:
>>> blob = """{
... '3' : { 'name' : 'a', 'spec' : 'b', 'start_year' : 'c', 'end_year' : 'd' },
... '4' : {
... '0' : { 'name' : 'Cisco', 'spec' : 'CCNA', 'start_year' : '2002', 'end_year' : '2003' },
... '1' : { 'name' : 'fiju', 'spec' : 'briju', 'start_year' : '1234', 'end_year' : '5678' },
... },
... }""">>> edu_type = eval(blob)
>>> edu_type
{'3': {'end_year': 'd', 'start_year': 'c', 'name': 'a', 'spec': 'b'}, '4': {'1': {'end_year': '5678', 'start_year': '1234', 'name': 'fiju', 'spec': 'briju'}, '0': {'end_year': '2003', 'start_year': '2002', 'name': 'Cisco', 'spec': 'CCNA'}}}
Now, is this the best way? Probably not. But it works and doesn't resort to regular expressions, which might technically be better but is definitely not a quicker option considering the time spent debugging and troubleshooting your pattern matching.
JSON is a good format to use for interstitial data transfer.
Python also has a json
module as part of the Standard Library. While that is more picky about the output you're parsing, it is more certainly the better way to go about it (albeit with more work involved).
Solution 4:
okay, so this is ghetto as hell, but here goes:
let's say your input is a list of tuples. say: input = [('edu_type[3][end_year]', 'd'), ...]
from collections import defaultdict
from re importcompiledefdefdict():
return defaultdict(defdict)
edu_type = defdict()
inputs = [(x.replace('[', '["').replace(']', '"]'), y) for x, y ininput]
forinputin inputs:
exec = '%s = "%s"' % input
Note that you should only use this if you trust the source of your input, as it is nowhere near safe.
Post a Comment for "Django, Python: Is There A Simple Way To Convert Php-style Bracketed Post Keys To Multidimensional Dict?"