Python:在字典中填充或向当前值添加值
我有以下形式的数据:Python:在字典中填充或向当前值添加值,python,dictionary,add,Python,Dictionary,Add,我有以下形式的数据: 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 =
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'
回溯(最近一次呼叫最后一次):
文件“/get_idmanager_stats.py”,第25行,在
如果d[a]:
KeyError:'00'
这就是集合。defaultdict的用途
你可以简单地做
d = defaultdict(int)
及
你会发现它在没有任何
if
语句的情况下工作。这很酷,但它没有给我say key 00的聚合值,而是给了我多行key00@Simply赛斯:什么?它计算一个总数。不是名单。你在说什么?我需要把打印循环再缩进一级。。。谢谢
d = collections.defaultdict(int)
for output in search_results:
a,b = output.split()
d[int(a)] += int(b)
d = collections.defaultdict(int)
for output in search_results:
a,b = output.split()
d[int(a)] += int(b)