【问题标题】:Python: Populate or add value to current value in a dictionaryPython:向字典中的当前值填充或添加值
【发布时间】:2011-09-13 01:55:28
【问题描述】:

我有

形式的数据
00 154
01 72
02 93
03 202
04 662
05 1297
00 256

我希望遍历每一行并将第 1 列中的值设为键,将第 2 列中的值设为值

如果当前键已经存在,则以数学方式将第 2 列的新值添加到第 2 列的当前值。

试过这个:

search_result = searches.stdout.readlines()
      for output in search_result:
        a,b =  output.split()
        a = a.strip()
        b = b.strip()

        if  d[a]:
         d[a] = d[a] + b
        else:
         d[a] = b

得到了这个:

Traceback (most recent call last):
  File "./get_idmanager_stats.py", line 25, in <module>
    if  d[a]:
KeyError: '00'

【问题讨论】:

    标签: python dictionary add


    【解决方案1】:

    这就是collections.defaultdict 的用途。

    你可以这样做

    d = defaultdict(int)
    

    d[a]= d[a] + int(b)
    

    您会发现它无需任何if 语句即可工作。

    【讨论】:

    • 这很酷,但它没有给我说键 00 的聚合值,而是给了我键 00 的多行
    • @Simply Seth:什么?它计算一个总和。不是清单。你在说什么?
    • 我需要将打印循环再取消缩进一级...谢谢。
    【解决方案2】:
    d = collections.defaultdict(int)
    for output in search_results:
       a,b = output.split()
       d[int(a)] += int(b)
    

    【讨论】:

      猜你喜欢
      • 2020-12-06
      • 1970-01-01
      • 1970-01-01
      • 2020-06-10
      • 2018-05-27
      • 1970-01-01
      • 2016-11-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多