简体   繁体   English

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

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

I have a dictionary as: 我有一本字典:

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

I want the new nested dictionary to be made like this: 我希望新的嵌套字典是这样制作的:

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

I tried this: 我尝试了这个:

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)

Gives this error: 给出此错误:

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

As I mentioned in comments, nest_val is actually the value which is a string and doesn't have an items() method. 正如我在评论中提到的, nest_val实际上是一个字符串值,没有items()方法。 Besides that, you don't have to create another dictionary and update it by multiple loops like that. 除此之外,您不必创建另一个字典并通过多个循环来更新它。 Instead, you can create your desire dictionaries by one loop over the items. 取而代之的是,您可以通过循环遍历项目来创建您的期望词典。

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

And in a more Pythonic way you can just use a list comprehension to refuse appending to the list at each iteration. 而且,您可以使用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