search

Home  >  Q&A  >  body text

How does Python parse this data type? data__key__hello = "world"

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

黄舟黄舟2781 days ago691

reply all(2)I'll reply

  • 世界只因有你

    世界只因有你2017-05-18 10:56:23

    # 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)
    

    reply
    0
  • 巴扎黑

    巴扎黑2017-05-18 10:56:23

    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

    reply
    0
  • Cancelreply