Created
May 23, 2015 13:49
-
-
Save fellipeh/9d9b0698a4641030ecf8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import re | |
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment