1

I'm trying to convert this array

a = [
        ['A','B','C'],
        [1,33,45],
        [721,22,9]
    ]   

           

to a dictionary in order to have this output:

b = { 
    'A':[1,721],
    'B':[33,22],
    'C':[45,9]
}

My current code is like this, getting this error:

b = {}

for i in range(1,len(a)):
    for j in range(len(a[i])):
        b[a[0][j]].append(a[i][j])
        
Traceback (most recent call last):
File "<stdin>", line 3, in <module>
KeyError: 'A'           

May someone help me in how would be a way to do it. Thanks

jizhihaoSAMA
  • 12,336
  • 9
  • 27
  • 49
Ger Cas
  • 2,188
  • 2
  • 18
  • 45

3 Answers3

2

You can do this with a nested dictionary comprehension, looping first over the key values in a[0] and then the individual values in the other lists in a:

b = { k : [a[j][i] for j in range(1, len(a))] for i, k in enumerate(a[0]) }

Output:

{'A': [1, 721], 'B': [33, 22], 'C': [45, 9]}
Nick
  • 138,499
  • 22
  • 57
  • 95
2

Try this:

from collections import defaultdict


result = defaultdict(list)

for i in a[1:]:  # start from second list
    for k, v in zip(a[0], i):
        result[k].append(v)

print(dict(result))  # {'A': [1, 721], 'B': [33, 22], 'C': [45, 9]}
Ronie Martinez
  • 1,254
  • 1
  • 10
  • 14
2

Found your issue:

KeyError: 'A'

If you debugg it,you will find that: enter image description here But b is a empty dictionary,it surely will raise Exception.

Just followed by your code, you could just change

b = {}

to

from collections import defaultdict

....
b = defaultdict(list)

is okay.(The rest of the code does not need to be changed)


Other ideas:

b = dict(zip(a[0], zip(*a[1:]))) # {'A': (1, 721), 'B': (33, 22), 'C': (45, 9)}

b = dict(zip(a[0], map(list,zip(*a[1:])))) # {'A': [1, 721], 'B': [33, 22], 'C': [45, 9]}

b = dict(zip(a[0], [list(i) for i in zip(*a[1:])])) # {'A': [1, 721], 'B': [33, 22], 'C': [45, 9]}
jizhihaoSAMA
  • 12,336
  • 9
  • 27
  • 49
  • Thanks for your help. I select your solution because of the other ways you shared. In which application did you do the debug? And what does mean the asterisk in `zip` comand? – Ger Cas Jul 01 '20 at 04:18
  • 1
    @GerCas `the asterisk` seems like `unzip`.You could refer to [here](https://stackoverflow.com/questions/36901/what-does-double-star-asterisk-and-star-asterisk-do-for-parameters). – jizhihaoSAMA Jul 01 '20 at 04:21