Python 使用for循环向字典中的一个键添加多个值

Python 使用for循环向字典中的一个键添加多个值,python,dictionary,for-loop,Python,Dictionary,For Loop,我在使用的函数中使用了类似的方法。为什么在尝试执行此操作时会出现密钥错误 def trial(): adict={} for x in [1,2,3]: for y in [1,2]: adict[y] += x print(adict) adict开始时为空。不能将整数添加到不存在的值中。adict开始时为空。不能将整数添加到不存在的值。首次使用时,没有为adict[y]指定值 def trial(): adic

我在使用的函数中使用了类似的方法。为什么在尝试执行此操作时会出现密钥错误

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

adict
开始时为空。不能将整数添加到不存在的值中。

adict
开始时为空。不能将整数添加到不存在的值。

首次使用时,没有为
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}

第一次使用时,没有为
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]失败,因为它正在访问一个不存在的变量。

您应该像这样修改代码:

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]失败,因为它正在访问一个不存在的变量。

您没有为每个键初始化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(,{1:6,2:6})

您没有为每个键初始化
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(,{1:6,2:6})

您尝试使用
adict[y]+=x
adict[y]
添加内容,但是
adict[y]
在第一次尝试访问密钥时没有定义。您尝试使用
adict[y]+=x
adict[y]
添加内容,但是
adict[y]
在您第一次尝试访问密钥时未定义。详细说明,您的在位
adict[y]+=x
行就是问题所在。在第一次通过时,没有任何东西已经“就位”。更详细地说,您的就位
adict[y]+=x
行就是问题所在。第一次传递时没有任何内容已“就位”。不,
adict[y]
不是
None
,它不存在。这是两个不同的东西。不,
adict[y]
不是
None
,它不存在。这是两件不同的事情。