簡體   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