Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Three lists zipped into list of dicts

Tags:

Consider the following:

>>> # list of length n
>>> idx = ['a', 'b', 'c', 'd']

>>> # list of length n
>>> l_1 = [1, 2, 3, 4]

>>> # list of length n
>>> l_2 = [5, 6, 7, 8]

>>> # first key
>>> key_1 = 'mkt_o'

>>> # second key
>>> key_2 = 'mkt_c'

How do I zip this mess to look like this?

{
    'a': {'mkt_o': 1, 'mkt_c': 5},
    'b': {'mkt_o': 2, 'mkt_c': 6},
    'c': {'mkt_o': 3, 'mkt_c': 6},
    'd': {'mkt_o': 4, 'mkt_c': 7},
    ...
}

The closest I've got is something like this:

>>> dict(zip(idx, zip(l_1, l_2)))
{'a': (1, 5), 'b': (2, 6), 'c': (3, 7), 'd': (4, 8)}

Which of course has tuples as values instead of dictionaries, and

>>> dict(zip(('mkt_o', 'mkt_c'), (1,2)))
{'mkt_o': 1, 'mkt_c': 2}

Which seems like it might be promising, but again, fails to meet requirements.

like image 484
Jason Strimpel Avatar asked Mar 27 '18 07:03

Jason Strimpel


People also ask

Can you zip three lists?

Python zip three listsPython zipping of three lists by using the zip() function with as many inputs iterables required. The length of the resulting tuples will always equal the number of iterables you pass as arguments. This is how we can zip three lists in Python.

Are Dicts faster than lists?

A dictionary is 6.6 times faster than a list when we lookup in 100 items.

Can you zip a dictionary with a list Python?

Python's zip() function is defined as zip(*iterables) . The function takes in iterables as arguments and returns an iterator. This iterator generates a series of tuples containing elements from each iterable. zip() can accept any type of iterable, such as files, lists, tuples, dictionaries, sets, and so on.


2 Answers

{k : {key_1 : v1, key_2 : v2} for k,v1,v2 in zip(idx, l_1, l_2)}
like image 158
DYZ Avatar answered Oct 25 '22 22:10

DYZ


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 list

new_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}
 }
like image 20
Moinuddin Quadri Avatar answered Oct 26 '22 00:10

Moinuddin Quadri