1

I have a list of tuples with three elements:

A = [[(72, 1, 2), (96, 1, 4)], 
     [(72, 2, 1), (80, 2, 4)], 
     [], 
     [(96, 4, 1), (80, 4, 2), (70, 4, 5)],
     [(70, 5, 4)],
     ]

I need to convert it to a dictionary in this format (note that the second element in the tuple will be the key):

A_dict = { 1: {2:72, 4:96},
           2: {1:72, 4:80},
           3: {},
           4: {1:96, 2:80, 5:70},
           5: {4:70},
         }

Is there a way to convert A to A_dict?

I tried this:

A_dict = {b:{a:c} for a,b,c in A}

but I got an error:

ValueError: not enough values to unpack (expected 3, got 2)

bphi
  • 3,115
  • 3
  • 23
  • 36
user9439906
  • 433
  • 2
  • 7
  • 17

2 Answers2

3

You can just do:

A_dict = {k+1: {t[2]: t[0] for t in l} for k, l in enumerate(A)}

>>> A_dict
{
 1: {2: 72, 4: 96}, 
 2: {1: 72, 4: 80}, 
 3: {}, 
 4: {1: 96, 2: 80, 5: 70}, 
 5: {4: 70}
}
bphi
  • 3,115
  • 3
  • 23
  • 36
  • While this works on the OP's stated input, I'm not sure we can take for granted that the second element of each tuple is always one greater than its index in A. In other words, `k+1` seems like a brittle solution for determining the key of `A_dict`. – Kevin Dec 04 '18 at 20:56
  • @Kevin Doesn't `k` come from `enumerate` though? – Cole Dec 04 '18 at 21:08
2

By iterating on the indices of the list, according to its length. And for each value building its own dictionary:

A_dict = {i + 1 : {v[2] : v[0] for v in A[i]} for i in range(len(A))}

will output:

{1: {2: 72, 4: 96},
 2: {1: 72, 4: 80},
 3: {},
 4: {1: 96, 2: 80, 5: 70},
 5: {4: 70}}

Actually your desired code is:

A_dict = {A[i][0][1] : {v[2] : v[0] for v in A[i]} for i in range(len(A)) if len(A[i]) > 0}

But that will 'skip' the third line, as there is no list, thus not able to determinate the actual key, according to your specification.

Dinari
  • 2,487
  • 13
  • 28
  • While this works on the OP's stated input, I'm not sure we can take for granted that the second element of each tuple is always one greater than its index in A. In other words, `i+1` seems like a brittle solution for determining the key of `A_dict`. – Kevin Dec 04 '18 at 20:56
  • You are correct, but that is not consistent with his expected output, I will, however, fix this. – Dinari Dec 04 '18 at 21:00