Home > database >  convert nested list to nested dictionary when value is not present create new dictionary
convert nested list to nested dictionary when value is not present create new dictionary

Time:01-10

input data

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

whenever there is blank in value,we should create new dictionary..

o/p like

{
    “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)

CodePudding user response:

try this:

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]})

which outputs this:

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