![](/img/trans.png)
[英]How to Append a 2nd value to an existing key in a dictionary in Python in a Loop
[英]how append (key,value) with loop on python
我想創建一個帶有循環的新字典,但我找不到使用 append 在循環中推送鍵和值的方法。 我嘗試這樣的事情,但我仍在尋找好方法。
frigo = {"mangue" : 2, "orange" : 8, "cassoulet" : 1, "thon" : 2, "coca" : 8, "fenouil" : 1, "lait" : 3}
new_frigo = {}
for i, (key, value) in enumerate(frigo.items()):
print(i, key, value)
new_frigo[i].append{key,value}
已經有一個 python function :
new_frigo.update(frigo)
無需循環! dict.update(other_dict)
只是將other_dict
的所有內容添加到dict
。
無論如何,如果你出於某種原因想用循環來做,
for key, value in frigo.items():
new_frigo[key] = value
會這樣做。 在這里使用i
沒有意義 - 字典new_frigo
沒有索引,但有鍵。
您可以使用update
append 字典中的鍵和值如下:
frigo = {"mangue": 2, "orange": 8, "cassoulet": 1, "thon": 2, "coca": 8, "fenouil": 1, "lait": 3}
new_frigo = {}
for i, (key, value) in enumerate(frigo.items()):
new_frigo.update({key:value})
print(new_frigo)
結果:
{'mangue': 2, 'orange': 8, 'cassoulet': 1, 'thon': 2, 'coca': 8, 'fenouil': 1, 'lait': 3}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.