简体   繁体   中英

Transform string keys into dict

how can i transform:

{'leads[update][0][id]': '57558587'}

into this

{'leads': {
    'update': [
        {'id':'57558587'}]

    }
}

I can solve this using regex, but i'm curious if there is more pythonic solution

I would do something like

import re
from pprint import pprint

in_data = {
    "leads[update][0][id]": "57558587",
    "leads[update][0][name]": "john",
    "leads[update][1][id]": "12345678",
    "leads[update][1][name]": "peasoup",
    "leads[update][yes][hello]": "greetings",
}


def transform(root, key, value):
    bits = [bit for bit in re.split(r"[\[\]]+", key) if bit]
    final_key = bits.pop()
    for bit in bits:
        root = root.setdefault(bit, {})
    root[final_key] = value


out_data = {}

for key, value in in_data.items():
    transform(out_data, key, value)

pprint(out_data)

This outputs

{'leads': {'update': {'0': {'id': '57558587', 'name': 'john'},
                      '1': {'id': '12345678', 'name': 'peasoup'},
                      'yes': {'hello': 'greetings'}}}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM