python - 通过标准迭代总结值并存储到字典中

标签 python dictionary

我有以下数据:

foo a 199
foo b 200
foo c 300
foo a 103
foo b 400
foo c 120
bar a 100
bar b 100
bar c 100

我想要得到的是一本如下所示的字典:

{foo:{a:302,   # 199 + 103
      b:600,   # 200 + 400
      c:420,}, # 300 + 120
 bar:{a:100,
      b:100,
      c:100}}

我被这段代码困住了:

import csv
from collections import defaultdict

outerdict = defaultdict(dict)
with open('myinputabove.txt','r') as tsvfile:
    tabheader = csv.reader(tsvfile,delimeter=" ")
    for row in tabheader:
        val1 = row[0]
        val2 = row[1]
        val3 = row[2]
        outerdict[val1][val2] += val3

最佳答案

你走在正确的道路上。对代码进行一些修改即可解决问题。

  • 当您使用 csv 模块进行解析时,每个元素都是一个字符串。那么你 在添加之前必须将 val3 转换为 int。
  • 您必须处理向内部字典添加元素时可能出现的KeyError

以下代码有效:

outerdict = defaultdict(dict)
with open('file.txt','r') as tsvfile:
    tabheader = csv.reader(tsvfile, delimiter=" ")
    for row in tabheader:
        val1 = row[0]
        val2 = row[1]
        val3 = row[2]
        try:
            outerdict[val1][val2] += int(val3)
        except KeyError:
            outerdict[val1][val2] = int(val3)

关于python - 通过标准迭代总结值并存储到字典中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22448376/

相关文章:

Python zeromq——单个订阅者的多个发布者?

python - 如何使用 Python 检查我的服务器是否正常运行?

python - 如何在Python中使用变量的值作为类型提示

python - 在 lldb Python 脚本中取消引用类型为 void * 的 SBValue

python - 如何从字典中仅提取某些值(python)

python - 如何在 pandas 中按日期分组并创建与日期关联的时间列

javascript - 创建 html 表的另一种方法

ios - 如何使用控制台输出来使用 if 条件?

python - 你能阻止函数在 python 的字典映射中执行吗?

python - 更改 python 键的类型