Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/319.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.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_List_Dictionary - Fatal编程技术网

将列表列表转换为字典词典(Python)

将列表列表转换为字典词典(Python),python,list,dictionary,Python,List,Dictionary,假设我有一个列表X=[[2,2]]、[[2,5]、[3,1]]、[[3,3]、[4,4]、[1,6]]、[[1,1]、[4,0]]、[[]]。我想把X转换成这样一本词典 G = {0: {2: 2}, 1: {2: 5, 3: 1}, 2: {3: 3, 4: 4, 1: 6}, 3: {1: 1, 4: 0}, 4: {} } 到目前为止我有 for i in range(0,len(X)): for j in range(0, len

假设我有一个列表
X=[[2,2]]、[[2,5]、[3,1]]、[[3,3]、[4,4]、[1,6]]、[[1,1]、[4,0]]、[[]]
。我想把
X
转换成这样一本词典

G = {0: {2: 2},
     1: {2: 5, 3: 1},
     2: {3: 3, 4: 4, 1: 6},
     3: {1: 1, 4: 0},
     4: {}
    }
到目前为止我有

for i in range(0,len(X)):
    for j in range(0, len(X[i])):
        G[i] = {X[i][j][0]: X[i][j][1]}
产生

{0: {2: 2}}
{0: {2: 2}, 1: {2: 5}}
{0: {2: 2}, 1: {3: 1}}
{0: {2: 2}, 1: {3: 1}, 2: {3: 3}}
{0: {2: 2}, 1: {3: 1}, 2: {4: 4}}
{0: {2: 2}, 1: {3: 1}, 2: {1: 6}}
{0: {2: 2}, 1: {3: 1}, 2: {1: 6}, 3: {1: 1}}
{0: {2: 2}, 1: {3: 1}, 2: {1: 6}, 3: {4: 0}}
Traceback (most recent call last):
G[i] = {X[i][j][0]: X[i][j][1]}
IndexError: list index out of range
首先,它只更新字典,而不添加新的键,其次,它在我的空列表中失败。

有什么建议吗?

您分配给
G
的任务应该是:

G[i][X[i][j][0]] = X[i][j][1]
您需要在内部循环之前初始化
G
的每个项:

G[i] = {}

如果您使用的是Python2.7,那么可以使用字典理解

X =  [[[2, 2]], [[2, 5], [3, 1]], [[3, 3], [4, 4], [1, 6]], [[1, 1], [4, 0]], [[]]]

d = {k: dict(v) if v[0] else {} for k, v in enumerate(X)}
有人有一个很好的答案,但他们删除了它,他们也使用字典理解,但处理空列表更好(我想)。事情是这样的

d = {k: dict(item for item in v if item) for k, v in enumerate(X)}

美好的这甚至在Python3中也适用。我真的需要花更多的时间在列表和字典理解上。非常感谢。