簡體   English   中英

使用for循環將多個值添加到字典中的一個鍵

[英]Add multiple values to one key in dictionary with for loop

我正在使用的函數中使用類似的方法。 嘗試執行此操作時為什么會出現關鍵錯誤?

def trial():
     adict={}
     for x in [1,2,3]:
          for y in [1,2]:
               adict[y] += x
print(adict)

adict開始是空的。 您不能將整數添加到尚不存在的值。

您沒有為每個鍵初始化adict 您可以使用defaultdict解決此問題:

from collections import defaultdict
def trial():
    adict=defaultdict(int)
    for x in [1,2,3]:
        for y in [1,2]:
            adict[y] += x
    print(adict)
trial()

結果為defaultdict(<class 'int'>, {1: 6, 2: 6})

首次使用adict[y]時,沒有分配任何值。

def trial():
     adict={}
     for x in [1,2,3]:
          for y in [1,2]:
               if y in adict: # Check if we have y in adict or not 
                   adict[y] += x
               else: # If not, set it to x
                   adict[y] = x
     print(adict)

輸出:

>>> trial()
{1: 6, 2: 6}

您應該像這樣修改您的代碼:

def trial():
   adict={0,0,0}
   for x in [1,2,3]:
      for y in [1,2]:
           adict[y] += x
print(adict)

“ adict”沒有任何條目。 因此adict [1]失敗,因為它正在訪問不存在的變量。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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