at0736
at0736

Reputation: 23

Merge lists into a list of dictionaries

I have three lists and three keys for each list, and would like to convert them into a list of dictionaries.

list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
list3 = [5.0, 6.0, 7.0]
keys = ['key1', 'key2', 'key3']

my expected output is this,

[[{'key1': 1, 'key2': 'a', 'key3': 5.0}], 
 [{'key1': 2, 'key2': 'b', 'key3': 6.0}], 
 [{'key1': 3, 'key2': 'c', 'key3': 7.0}]]

What's the most pythonic way of achieving this output?

Upvotes: 2

Views: 300

Answers (3)

Carmoreno
Carmoreno

Reputation: 1319

In this solution, the idea is to reduce all problem to only one dictionary with the following way: {key: array_to_assign}

from functools import reduce
from collections import OrderedDict

list_response = [] 
list_dicts = []
list_values = [list1, list2, list3]

for index, k in enumerate(keys):
    list_dicts.append(
          OrderedDict({k: list_values[index]})
    )
my_dictionary = reduce(lambda d1, d2: OrderedDict(list(d1.items()) + list(d2.items())) , list_dicts)

Finally, we iterate the dictionary and assign the nested list's item to the correct key.

for key, value in my_dictionary.items():
    for i in value:
        list_response.append({
            key: i
        })
print(list_response)

Output:

[
   {'key1': 1}, 
   {'key1': 2}, 
   {'key1': 3}, 
   {'key2': 'a'}, 
   {'key2': 'b'}, 
   {'key2': 'c'}, 
   {'key3': 5.0}, 
   {'key3': 6.0}, 
   {'key3': 7.0}
]

Upvotes: 0

Lucas Mior
Lucas Mior

Reputation: 68

list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
list3 = [5.0, 6.0, 7.0]
keys = ['key1', 'key2', 'key3']
lists = [list1, list2, list3]


result = []

for list in lists: 
    d = {}
    for i, j in zip(keys, list):
        d[i] = j
    result.append([d])

print(result)

Upvotes: 0

Andrej Kesely
Andrej Kesely

Reputation: 195418

Try:

list1 = [1, 2, 3]
list2 = ["a", "b", "c"]
list3 = [5.0, 6.0, 7.0]
keys = ["key1", "key2", "key3"]

out = []
for t in zip(list1, list2, list3):
    out.append([dict(zip(keys, t))])

print(out)

Prints:

[[{'key1': 1, 'key2': 'a', 'key3': 5.0}], 
 [{'key1': 2, 'key2': 'b', 'key3': 6.0}], 
 [{'key1': 3, 'key2': 'c', 'key3': 7.0}]]

Or:

out = [[dict(zip(keys, t))] for t in zip(list1, list2, list3)]
print(out)

Upvotes: 4

Related Questions