How does Python parse this data type? data__key__hello = "world"
黄舟
黄舟 2017-05-18 10:54:23
0
2
640

For example, there is such a dictionary:

{
    'data__key_hello': "world",
    'data__key_bar': "foo",
    'data__a': "b",
    'b': 'c',
}

becomes

after conversion
{
    'data': {
        'key': {
            'hello': 'world',
            'bar': 'foo'
        },
        'a': 'b',
    },
    'b': 'c'
}

is divided by an underscore

黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

reply all(2)
世界只因有你
# coding: utf-8

def parse_dict(obj={}):
    result = {}
    for key in obj:
        value = obj[key]
        parse_key_value(key, value, result)                
    return result

def parse_key_value(key, value, result={}):
    if not key:
        return

    head = ''
    while 1:
        head, _, tail = key.partition('_') 
        if head:
            break
        key = tail

    if head not in result:
        if tail:
            result[head] = {} 
        else:
            result[head] = value
            return 
    
    parse_key_value(tail, value, result[head])

obj = {
    'data__key_hello': "world",
    'data__key_bar': "foo",
    'data__a': "b",
    'b': 'c',
}

print parse_dict(obj)
巴扎黑

Just make do with it

d = {
    'data__key_hello': "world",
    'data__key_bar': "foo",
    'data__a': "b",
    'b': 'c',
}

n = {}
for k, v in d.items():
    keys = k.replace('__', '_').split('_')
    child = n
    for i, key in enumerate(keys):
        child = child.setdefault(key, {} if i < len(keys) - 1 else v)

print n
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!