nodes_g = {}
with open("calls.txt") as fp3:
for line in fp3:
rows3 = line.split(";")
x, node1, node2, sec, y = line.split(";")
if node1 not in nodes_g:
nodes_g[node1, node2] = int(rows3[3])
elif node1 in nodes_g and node2 in nodes_g:
nodes_g[node1, node2] += int(rows3[3])
print(nodes_g)
我现在有这个,其中node1正在呼叫号码,而node2正在接收号码,而sec或者行3 [3]是这两个号码之间相互谈话的秒数。我想使用文件的第三行更新dict的值(通话秒数),但不是更新它,而是将其替换为下一行3的值,依此类推。
链接到calls.txt文件:http://pastebin.com/RSMnXDtq
答案 0 :(得分:1)
这是因为使用nodes_g[node1,node2]
隐式将密钥转换为元组(node1, node2)
。这样说,条件检查node1 not in nodes_g
总是假的,因为你将元组或对存储为键而不是单个节点。
您应该执行以下操作:
from collections import Counter
nodes_g = Counter()
with open("test.txt") as fp3:
for line in fp3:
x, node1, node2, sec, y = line.split(";")
# Missing keys default to 0.
nodes_g[node1, node2] += int(sec)
print(nodes_g)