【发布时间】:2016-01-10 04:57:35
【问题描述】:
我的数据如下,
graph = {'1':{'2':[0,5]}, '2':{'4':[16,68]}}
即使下面的代码适用于我的 IDLE
d = {1 : {2 : [15,20]}}
d[1][3] = [1,6]
print d[1][3]
但是当我尝试从屏幕读取并从输入中填充我的数据集时,我得到了错误 我的循环是这样的
graph = {}
Q = {}
N,M,T=map(int,raw_input().split())
for i in range(0,M):
x,y,t1,t2=map(int,raw_input().split())
graph[x][y] = [t1,t2]
print graph
来自屏幕的输入是格式,其中第一行中的第二个变量是下面的行数,即没有。循环的次数,在下面的情况下为 5
4 5 20
1 2 15 20
1 3 1 6
2 4 25 30
3 4 2 7
3 4 30 35
以上输入应使数据集为
graph = {'1':{'2':[15,20], '3':[1,6]}, '2':{'4':[25,30]}, '3':{'4':[2,7], '4':[30,35]}}
谁能告诉我循环中缺少什么? 谢谢
【问题讨论】:
-
你不能索引到一个不存在的字典,例如
graph[1]是 KeyError。您可以使用来自collections的defaultdict,例如graph = defaultdict(dict)
标签: python json python-2.7 loops dictionary