简体   繁体   English

如何将字典更改为嵌套字典

[英]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.我可以把它做成嵌套字典,但是 python 自动将最后两个 Polyester 合二为一,它重复嵌套 zip dic 三次。 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}}

You don't need a list comprehension for split .您不需要列表理解split Just split val .只需拆分val

And then you don't need to zip anything when creating the dictionary.然后在创建字典时不需要 zip 任何东西。

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

You could use str.rsplit with maxsplit=1 for each value and convert it to a dict while you traverse mat_dict :您可以将str.rsplitmaxsplit=1一起用于每个值,并在遍历mat_dict时将其转换为字典:

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

Output: Output:

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

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: Output:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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