-1

i'm trying to get this output:

[{'A':{'a':1, 'b':2, 'c':3}}, {'B':{'a':4, 'b':5, 'c':6}}]

from this:

list1 = [[1,2,3],[4,5,6]]
list2 = ['a','b','c']
list3 = ['A','B']

And i tried this:

list1 = [[1,2,3],[4,5,6]]
list2 = ['a','b','c']
list3 = ['A','B']
main_list =[]
for i in range(len(list1)):
    db1 = dict(zip(list2,list1[i]))
    for j in range(len(list3)):
        db2 = dict(zip(list3[j],db1))
        main_list.append(db2)   
print(main_list)

Any help would be really appreciated

  • 4
    `db1 = dict(zip(list2,list1[i])` is missing a closing `)` – roganjosh May 28 '20 at 14:31
  • 2
    Fixing that will allow your code to run but it won't give your desired output. However, perhaps that's enough to be able to explore the issue yourself. – roganjosh May 28 '20 at 14:33
  • Possible duplicate of [python - 'Syntax Error: invalid syntax' for no apparent reason - Stack Overflow](https://stackoverflow.com/questions/24237111/syntax-error-invalid-syntax-for-no-apparent-reason) – user202729 May 28 '20 at 14:35
  • i fixed it but still didn't give me the wanted output –  May 28 '20 at 14:35
  • update the question accrdingly – Tomerikoo May 28 '20 at 14:39

1 Answers1

2

This could be done more compactly using the below list comprehension. Essentially you start by element-wise zipping list3 (your keys) against list1 which will have your sublists. Then for each of those pairs, you zip list2 (which will be the inner keys) against the current sublist, which will serve as the values of the inner dictionary.

>>> [{k: dict(zip(list2, sub))} for k,sub in zip(list3, list1)]
[{'A': {'a': 1, 'b': 2, 'c': 3}}, {'B': {'a': 4, 'b': 5, 'c': 6}}]

For what it's worth, the issue with your current code is simply a missing ) above the line that you indicated. However, a more terse way to achieve your desired output would be using the above list comprehension.

Cory Kramer
  • 114,268
  • 16
  • 167
  • 218