1

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?

sebastian
  • 478
  • 8
  • 22

2 Answers2

3

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)}
John
  • 13,197
  • 7
  • 51
  • 101
  • nice. that even works in Python 3. I really need to spend more time on list and dictionary comprehensions. Thank you. – sebastian May 12 '15 at 14:48
0

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] = {}
Scott Hunter
  • 48,888
  • 12
  • 60
  • 101