Skip to content

Instantly share code, notes, and snippets.

@cauethenorio
Last active August 29, 2015 14:21
Show Gist options
  • Save cauethenorio/7b9ca57ed5cb856ed55e to your computer and use it in GitHub Desktop.
Save cauethenorio/7b9ca57ed5cb856ed55e to your computer and use it in GitHub Desktop.
converter inputs de array (PHP) para um dict python
# coding: utf8
import re
from functools import reduce
def merge_dicts(*dicts):
# http://stackoverflow.com/questions/7204805/dictionaries-of-dictionaries-merge
if not reduce(lambda x, y: isinstance(y, dict) and x, dicts, True):
raise TypeError("Object in *dicts not of type dict")
if len(dicts) < 2:
raise ValueError("Requires 2 or more dict objects")
def merge(a, b):
for d in set(a.keys()).union(list(b.keys())):
if d in a and d in b:
if type(a[d]) == type(b[d]):
if not isinstance(a[d], dict):
ret = list({a[d], b[d]})
if len(ret) == 1: ret = ret[0]
yield (d, sorted(ret))
else:
yield (d, dict(merge(a[d], b[d])))
else:
raise TypeError("Conflicting key:value type assignment")
elif d in a: yield (d, a[d])
elif d in b: yield (d, b[d])
else:
raise KeyError
return reduce(lambda x, y: dict(merge(x, y)), dicts[1:], dicts[0])
def convert_php_array_to_python_dict(forms_tuple):
regexp = r'(?:^([a-zA-Z0-9_]*)|\[([a-zA-Z0-9_]+)\])'
root = {}
for raw_field, value in forms_tuple:
matches = re.findall(regexp, raw_field)
keys = [k1 or k2 for k1, k2 in matches]
for i, key in enumerate(reversed(keys)):
field = {key if not key.isdigit() else int(key): value.strip() if i == 0 else field}
root = merge_dicts(root, field)
return root
if __name__ == '__main__':
from django.conf import settings
settings.configure() ## necessário para usar o QueryDict fora de uma aplicação Django
from django.http import QueryDict
querydict = QueryDict("data[id]=D6adasd7065C2C0A84C96B47EA17705991B14&data[status]=paid&event=invoice")
print(convert_php_array_to_python_dict(querydict.items()))
# {'event': 'invoice', 'data': {'id': 'D6adasd7065C2C0A84C96B47EA17705991B14', 'status': 'paid'}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment