Sim*_*eth -1 python dictionary add
我有数据的形式
00 154
01 72
02 93
03 202
04 662
05 1297
00 256
Run Code Online (Sandbox Code Playgroud)
我希望遍历每一行,并将第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
Run Code Online (Sandbox Code Playgroud)
得到了这个:
Traceback (most recent call last):
File "./get_idmanager_stats.py", line 25, in <module>
if d[a]:
KeyError: '00'
Run Code Online (Sandbox Code Playgroud)
这collections.defaultdict是为了什么.
你可以干脆做
d = defaultdict(int)
Run Code Online (Sandbox Code Playgroud)
和
d[a]= d[a] + int(b)
Run Code Online (Sandbox Code Playgroud)
你会发现它没有任何if陈述.