Rumah  >  Soal Jawab  >  teks badan

Bagaimanakah Python menghuraikan jenis data ini data__key__hello = "dunia"?

Sebagai contoh, terdapat kamus seperti:

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

Selepas penukaran ia menjadi

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

Ia dibahagikan dengan garis bawah

黄舟黄舟2711 hari yang lalu626

membalas semua(2)saya akan balas

  • 世界只因有你

    世界只因有你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)
    

    balas
    0
  • 巴扎黑

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

    Selesai sahaja

    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

    balas
    0
  • Batalbalas