繁体   English   中英

如何在特定格式的python中将字典合并为嵌套字典?

[英]How to merge a dict into nested dict in python with particular format?

我有一本字典:

digit = { 'one' : 1, 'two' : 2, 'three' : 3, 'four' : 4, 'five' : 5 }

我希望新的嵌套字典是这样制作的:

new_dict = [{'eng':'one','math': 1}
            {'eng':'two','math': 2}
            {'eng':'three','math': 3}
            {'eng':'four','math': 4}
            {'eng':'five','math': 5}
           ]

我尝试了这个:

digit = { 'one' : 1, 'two' : 2, 'three' : 3, 'four' : 4, 'five' : 5 }
new_dict={'eng':'','math':''}

for nest_key,nest_val in new_dict.items():
    for (key,value),(k,v) in nest_val.items(), digit.items():
        if nest_val['eng'] == '':
            nest_val.update({k:v})  
        nest_val.append({k:v})

print(new_dict)

给出此错误:

  for (key,value),(k,v) in nest_val.items(), digit.items():  
AttributeError: 'str' object has no attribute 'items'

正如我在评论中提到的, nest_val实际上是一个字符串值,没有items()方法。 除此之外,您不必创建另一个字典并通过多个循环来更新它。 取而代之的是,您可以通过循环遍历项目来创建您的期望词典。

lst = []
for name, val in digit.items():
    lst.append({'eng': name,'math': val})

而且,您可以使用Python方式,使用列表推导来拒绝每次迭代时追加到列表。

lst = [{'eng': name,'math': val} for name, val in digit.items()]

暂无
暂无

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

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