简体   繁体   English

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

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

I'm using a similar method in a function I'm using. 我正在使用的函数中使用类似的方法。 Why do I get a key error when I try to do this? 尝试执行此操作时为什么会出现关键错误?

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

adict starts off empty. adict开始是空的。 You can't add an integer to a value that doesn't already exist. 您不能将整数添加到尚不存在的值。

You did not initialize adict for each key. 您没有为每个键初始化adict You can use defaultdict to solve this issue: 您可以使用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()

The result is defaultdict(<class 'int'>, {1: 6, 2: 6}) 结果为defaultdict(<class 'int'>, {1: 6, 2: 6})

There is no value assigned to adict[y] when you first use it. 首次使用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)

Output: 输出:

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

You should modify youre code like this: 您应该像这样修改您的代码:

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

"adict" has no entries. “ adict”没有任何条目。 So adict[1] fails because it is accessing a variable that does not exist. 因此adict [1]失败,因为它正在访问不存在的变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM