'how to change a dictionary into nested dictionary
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}}
Solution 1:[1]
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] = {' '.join(split[:-1]): float(split[-1].strip('%'))}
Solution 2:[2]
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}}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Funpy97 |
