繁体   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