Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/amazon-s3/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在嵌套字典python中输入数据_Python_Json_Python 2.7_Loops_Dictionary - Fatal编程技术网

在嵌套字典python中输入数据

在嵌套字典python中输入数据,python,json,python-2.7,loops,dictionary,Python,Json,Python 2.7,Loops,Dictionary,我的数据如下: graph = {'1':{'2':[0,5]}, '2':{'4':[16,68]}} 即使下面的代码在我的空闲时间工作 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,

我的数据如下:

graph = {'1':{'2':[0,5]}, '2':{'4':[16,68]}}
即使下面的代码在我的空闲时间工作

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
来自屏幕的输入格式为,其中第1行中的第2个变量是下面的行数,即循环次数,在下面的情况下为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[x][y] = [t1,t2]
还没有
graph[x]
,它不会自动为您将
graph[x]
设置为字典,您需要手动设置

一种简单的方法是使用新字典设置
x
键,如果键在
graph
中不存在,则使用字典设置
x
键,否则将返回键的值。范例-

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.setdefault(x, {})[y] = [t1,t2]
print graph
以上代码的演示结果-

4 5 20
1 2 15 20
1 3 1 6
2 4 25 30
3 4 2 7
3 4 30 35
{1: {2: [15, 20], 3: [1, 6]}, 2: {4: [25, 30]}, 3: {4: [30, 35]}}

您无法索引到不存在的词典,例如,
graph[1]
是一个关键错误。您可以使用
collections
中的
defaultdict
,例如
graph=defaultdict(dict)
感谢您的回复,如果您注意到我的数据集的键是字符串{'1':{'2':[15,20]}。。。怎么做?使用
str(x)
str(y)
?或者首先不要将它们映射到int?这取决于你想用它们做什么,但字典不能有重复的键,这是肯定的。顺便说一句,该列表无效,你在找元组列表吗?列表不能有
[4:[0,1]..
。如果您想要元组列表而不是
[4:[0,1]..
列表,可以在
.setdefault()中使用
[]
创建列表,然后附加元组,而不是现在正在执行的操作。