使用元组作为字典键和更新值
Using tuples as dict keys and updating value
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 或 rows3[3] 是两个号码之间通话的秒数。我想使用文件的第三行更新 dict 的值(通话秒数),但是不是更新它,而是用下一行的第 3 行值替换它,依此类推。
link 到 calls.txt 文件:http://pastebin.com/RSMnXDtq
这是因为使用 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)
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 或 rows3[3] 是两个号码之间通话的秒数。我想使用文件的第三行更新 dict 的值(通话秒数),但是不是更新它,而是用下一行的第 3 行值替换它,依此类推。
link 到 calls.txt 文件:http://pastebin.com/RSMnXDtq
这是因为使用 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)