繁体   English   中英

将键/值对列表转换为嵌套字典

[英]Convert list of key/value pairs to nested dictionary

输入数据:

data = [
    ['QR', ''],
    ['Cust', ''],
    ['fea', 'restroom'],
    ['chain', 'pa'],
    ['store', 'cd'],
    ['App', ''],
    ['End', 'EndnR'],
    ['Request', '0'],
    ['Sound', '15'],
    ['Target', '60'],
    ['Is', 'TRUE']
]

我想把它变成一本字典,每个空白值表示一个新的嵌套子字典的开始。

所需的 output:

{
    'QR': {
            'Cust': { 
                'fea': 'restroom ',
                'chain': 'pa',
                'store': 'cd'
            },
            'App': {
                'End': 'EndnR',
                'Request': '0',
                'Sound': '15',
                'Target': '60',
                'Is': 'true'
            },
    }
}

到目前为止,这是我的代码:

from collections import defaultdict
res = defaultdict(dict)
for i in data:
    res[i[0]] = i[1]
print(res)

但它只会创建一个带有一些空白值的平面字典,而不是嵌套字典。

尝试这个:

result = {}
nbr_keys = 0
keys = [ item[0] for item in data if item[1] == "" ]

for index, item in enumerate(data):
    
    if index == 0:
        if item[1] == "":
            key = item[0]
            di[item[0]] = {}
    else:
        
        if item[1] == "":
            di[key].update({item[0]: {}})
            nbr_keys +=1
            
        else:
            di[key][keys[nbr_keys]].update({item[0]: item[1]})

输出这个:

{'QR': {'Cust': {'fea': 'restroom', 'chain': 'pa', 'store': 'cd'},
  'App': {'End': 'EndnR',
   'Request': '0',
   'Sound': '15',
   'Target': '60',
   'Is': 'TRUE'}}}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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