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?
If you're using Python 2.7 you can use a dictionary comprehension.
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
Your assignment to
G
should be:And you'll need to initialize each item of
G
before the inner loop: