Converting list of lists of lists into dictionary

2019-08-10 11:40发布

Suppose I have a list X = [[[2, 2]], [[2, 5], [3, 1]], [[3, 3], [4, 4], [1, 6]], [[1, 1], [4, 0]], [[]]]. I want to convert X into a dictionary of dictionaries like so.

G = {0: {2: 2},
     1: {2: 5, 3: 1},
     2: {3: 3, 4: 4, 1: 6},
     3: {1: 1, 4: 0},
     4: {}
    }

So far I have

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]}

which produces

{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

First it only updates the dictionaries instead of appending new keys, second it fails me at my empty list.
Any suggestions?

2条回答
地球回转人心会变
2楼-- · 2019-08-10 11:53

If you're using Python 2.7 you can use a dictionary comprehension.

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)}

someone had a nice answer but they deleted it where they also used a dictionary comprehension but handled the empty lists better (I think). It went like so

d = {k: dict(item for item in v if item) for k, v in enumerate(X)}
查看更多
甜甜的少女心
3楼-- · 2019-08-10 12:03

Your assignment to G should be:

G[i][X[i][j][0]] = X[i][j][1]

And you'll need to initialize each item of G before the inner loop:

G[i] = {}
查看更多
登录 后发表回答