0

I have 2 arrays, one of which is two level:

lst1 = [1, 2, 3]

lst2 = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']]

How to make one list with dictionaries of them? like this:

dct = [{1:'a', 2:'b', 3:'c'}, {1:'d', 2:'e', 3:'f'}, {1:'g', 2:'h', 3:'i'}]

3 Answers3

2

here some cool way :

lst1 = [1, 2, 3]

lst2 = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']]
list_of_dicts = [{lst1[i]:x for i,x in enumerate(lst_tmp)} for lst_tmp in lst2 ]
list_of_dicts
>>> [{1: 'a', 2: 'b', 3: 'c'}, {1: 'd', 2: 'e', 3: 'f'}, {1: 'g', 2: 'h', 3: 'i'}]

or if you intentionally added curly braces and meant to use a set, it is impossible to turn it into a set because it is not hashable (although there some creative way to get it as in here)..

alretnativly you can also zip it!:

list_of_dicts = [dict(zip(lst1,lst_tmp)) for lst_tmp in lst2 ]
list_of_dicts
>>> [{1: 'a', 2: 'b', 3: 'c'}, {1: 'd', 2: 'e', 3: 'f'}, {1: 'g', 2: 'h', 3: 'i'}]
adir abargil
  • 5,495
  • 3
  • 19
  • 29
2

The output that you want is not a dictionary, but if you mean a list of dictionaries then you can use this compact form:

lst1 = [1, 2, 3]
lst2 = [["a", "b", "c"], ["d", "e", "f"], ["g", "h", "i"]]

dict_list = [dict(zip(lst1, lst2[i])) for i in range(len(lst2))]
Esi
  • 467
  • 3
  • 12
1

You can do this with zip, which combines two lists which can then be converted to a dict. You can do this in one line with list comprehension.

first = [1, 2, 3]
second = [["a", "b", "c"], ["d", "e", "f"], ["g", "h", "i"]]

print([dict(zip(first, item)) for item in second])

# [{1: 'a', 2: 'b', 3: 'c'}, {1: 'd', 2: 'e', 3: 'f'}, {1: 'g', 2: 'h', 3: 'i'}]

Without list comprehension:

first = [1, 2, 3]
second = [["a", "b", "c"], ["d", "e", "f"], ["g", "h", "i"]]

result = []

for item in second:
    result.append(dict(zip(first, item)))

print(result)

# [{1: 'a', 2: 'b', 3: 'c'}, {1: 'd', 2: 'e', 3: 'f'}, {1: 'g', 2: 'h', 3: 'i'}]

And a little bit more code, using enumerate:

first = [1, 2, 3]
second = [["a", "b", "c"], ["d", "e", "f"], ["g", "h", "i"]]

result = []

for sub in second:
    d = {}
    for index, item in enumerate(first):
        d[item] = sub[index]
    result.append(d)

print(result)

# [{1: 'a', 2: 'b', 3: 'c'}, {1: 'd', 2: 'e', 3: 'f'}, {1: 'g', 2: 'h', 3: 'i'}]
Cloudkollektiv
  • 11,852
  • 3
  • 44
  • 71