簡體   English   中英

append(鍵,值)如何在 python 上使用循環

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM