Three lists zipped into list of dicts
Solution 1: You may use zip
twice (actually thrice) with dictionary comprehension to achieve this as:
idx = ['a', 'b', 'c', 'd']l_1 = [1, 2, 3, 4]l_2 = [5, 6, 7, 8]keys = ['mkt_o', 'mkt_c'] # yours keys in another listnew_dict = {k: dict(zip(keys, v)) for k, v in zip(idx, zip(l_1, l_2))}
Solution 2: You may also use zip
with nested list comprehension as:
new_dict = dict(zip(idx, [{key_1: i, key_2: j} for i, j in zip(l_1, l_2)]))
Solution 3: using dictionary comprehension on top of zip
as shared in DYZ's answer:
new_dict = {k : {key_1 : v1, key_2 : v2} for k,v1,v2 in zip(idx, l_1, l_2)}
All the above solutions will return new_dict
as:
{ 'a': {'mkt_o': 1, 'mkt_c': 5}, 'b': {'mkt_o': 2, 'mkt_c': 6}, 'c': {'mkt_o': 3, 'mkt_c': 7}, 'd': {'mkt_o': 4, 'mkt_c': 8} }
You're working with dicts, lists, indices, keys and would like to transpose the data. It might make sense to work with pandas (DataFrame
, .T
and .to_dict
):
>>> import pandas as pd>>> idx = ['a', 'b', 'c', 'd']>>> l_1 = [1, 2, 3, 4]>>> l_2 = [5, 6, 7, 8]>>> key_1 = 'mkt_o'>>> key_2 = 'mkt_c'>>> pd.DataFrame([l_1, l_2], index=[key_1, key_2], columns = idx) a b c dmkt_o 1 2 3 4mkt_c 5 6 7 8>>> pd.DataFrame([l_1, l_2], index=[key_1, key_2], columns = idx).T mkt_o mkt_ca 1 5b 2 6c 3 7d 4 8>>> pd.DataFrame([l_1, l_2], index=[key_1, key_2], columns = idx).to_dict(){'a': {'mkt_o': 1, 'mkt_c': 5}, 'b': {'mkt_o': 2, 'mkt_c': 6}, 'c': {'mkt_o': 3, 'mkt_c': 7}, 'd': {'mkt_o': 4, 'mkt_c': 8}}