简体   繁体   中英

How to convert dictionaries to nested dictionary?

I have the dictionary as shown below:

dict1 = {'K7': ['k07 = v07', ''], 'K2': ['k02 = v02', ''], 'K01': ['k2 = v2', 'k02 = v2', ''], 'K3': ['k1 = v1', ''], 'K02': ['k2 = v2', '']}

I am trying to make a nested dictionary as follows:

dict1 = [{'K7': {'k07' : 'v07'}}, {'K2': {'k02' : 'v02'}}, {'K01': {'k2' : 'v2','k02' : 'v2'}, {'K3': {'k1' : 'v1'}}, {'K02': {'k2' : 'v2'}}]

This is the code that I have tried:

 dict2 = []
 for ks,vs in list(dict1.iteritems()):

     vs = filter(None, vs)
     vi1 = [i.split('=', 1)[0] for i in vs]
     vi2 = [i.split('=', 1)[1] for i in vs] 

     for v1, v2 in zip(vi1,vi2):
         dict2.append({ks : {v1 : v2}})

But, my output looks as below:

  dict2 = [{'K7': {'k07' : 'v07'}}, {'K2': {'k02' : 'v02'}}, {'K01': {'k2' : 'v2'}}, {'K01': {'k02' : 'v2'}}, {'K3': {'k1' : 'v1'}}, {'K02': {'k2' : 'v2'}}]

Pleased to hear some suggestions. Thanks a lot in advance.

You can use dict with a list comprehension:

dict1 = {'K7': ['k07 = v07', ''], 'K2': ['k02 = v02', ''], 'K01': ['k2 = v2', 'k02 = v2', ''], 'K3': ['k1 = v1', ''], 'K02': ['k2 = v2', '']}
new_d = [{a:dict(i.split(' = ') for i in b if i)} for a, b in dict1.items()]

Output:

[{'K7': {'k07': 'v07'}}, {'K2': {'k02': 'v02'}}, {'K01': {'k2': 'v2', 'k02': 'v2'}}, {'K3': {'k1': 'v1'}}, {'K02': {'k2': 'v2'}}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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