Home > front end >  how to change a dictionary into nested dictionary
how to change a dictionary into nested dictionary

Time:02-03

Hi I'm trying to write a dictionary into a nested form, but after I do some manipulation, the nested values do not match the form I'm looking for. Can anyone help me figure it out?

The original dictionary is:

mat_dict = {'Sole': 'Thermoplastic rubber 100%',
 'Upper': 'Polyester 100%',
 'Lining and insole': 'Polyester 100%'}

And I want the final form to be:

desired_dict = {'Sole': {'Thermoplastic rubber': 1.0},
 'Upper': {'Polyester':1.0},
 'Lining and insole': {'Polyester':1.0}}

The following is my code. I can make it into be nested dictionary, but python automatically combines the last two Polyester into one, and it repeats the nested zip dic three times. Does anyone know what happens and how to fix it?

for key,val in mat_dict.items():
    print(key)
    split = [i.split(' ') for i in cont_text]
    mat_dict[key] = dict(zip([' '.join(m[:-1]) for m in split],[float(m[-1].strip('%')) / 100.0 for m in split]))

# what I got is the following, which repeat the materials three times, and it didn't map each materials with my original clothing part
{'Sole': {'Thermoplastic rubber': 1.0, 'Polyester': 1.0},
 'Upper': {'Thermoplastic rubber': 1.0, 'Polyester': 1.0},
 'Lining and insole': {'Thermoplastic rubber': 1.0, 'Polyester': 1.0}}

CodePudding user response:

You don't need a list comprehension for split. Just split val.

And then you don't need to zip anything when creating the dictionary.

for key, val in mat_dict.items():
    split = val.split()
    mat_dict[key] = {split[:-1].join(' '): float(split[-1].strip('%'))}

CodePudding user response:

You could use str.rsplit with maxsplit=1 for each value and convert it to a dict while you traverse mat_dict:

out = {}
for key,val in mat_dict.items():
    k,v = val.rsplit(maxsplit=1)
    out[key] = {k: float(v.strip('%'))/100}

Output:

{'Sole': {'Thermoplastic rubber': 1.0},
 'Upper': {'Polyester': 1.0},
 'Lining and insole': {'Polyester': 1.0}}

CodePudding user response:

If you need a dictionary comprehension solution you can try the follow code:

mat_dict = {'Sole': 'Thermoplastic rubber 100%',
            'Upper': 'Polyester 100%',
            'Lining and insole': 'Polyester 100%'}

mat_dict = {k: {" ".join(v.split()[:len(v.split())-1]): float(v.split()[-1].replace("%", "")) / 100}
            for k, v in mat_dict.items()}

Output:

{'Sole': {'Thermoplastic rubber': 1.0}, 'Upper': {'Polyester': 1.0}, 'Lining and insole': {'Polyester': 1.0}}

  •  Tags:  
  • Related