-1

Input data:

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

I want to turn this into a dictionary, and each blank value indicates the start of a new, nested sub-dictionary.

Desired output:

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

Here is my code so far:

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

But it only creates a flat dictionary with some blank values, not a nested dictionary.

CrazyChucky
  • 3,263
  • 4
  • 11
  • 25
coder
  • 21
  • 4
  • 1
    Please read [how to ask a question](https://stackoverflow.com/help/how-to-ask) – Pynchia Jan 09 '23 at 11:30
  • I know one doesn't always have control over where one gets their data, but if possible you would make a change where the data is produced, so it gives you a sensible data structure to begin with. (Also, why not apply the same reasoning from my [answer](https://stackoverflow.com/a/75029750/12975140) to your very similar previous question? This is an almost identical starting structure.) – CrazyChucky Jan 09 '23 at 12:54
  • @CrazyChucky there is no option to change input data i – coder Jan 09 '23 at 18:03
  • Something I just noticed: how should the code know that `App` isn't inside `Cust`? How does the input data indicate the *end* of a sublevel? – CrazyChucky Jan 10 '23 at 04:35

1 Answers1

-1

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'}}}
kev_ta
  • 89
  • 2