Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a dictionary by zipping together two lists of uneven length [duplicate]

I have two lists different lengths, L1 and L2. L1 is longer than L2. I would like to get a dictionary with members of L1 as keys and members of L2 as values.

As soon as all the members of L2 are used up. I would like to start over and begin again with L2[0].

L1 = ['A', 'B', 'C', 'D', 'E']     L2 = ['1', '2', '3']     D = dict(zip(L1, L2))     print(D) 

As expected, the output is this:

{'A': '1', 'B': '2', 'C': '3'} 

What I would like to achieve is the following:

{'A': '1', 'B': '2', 'C': '3', 'D': '1', 'E': '2'} 
like image 316
Mat Avatar asked Jan 08 '19 16:01

Mat


People also ask

How do you create a dictionary using zip?

To create a dictionary from two sequences, use the dict() and zip() method. The dict(zip(keys, values)) needs the one-time global lookup each for dict and zip. Still, it doesn't create any needless intermediary data structures or deal with local lookups in function applications.


Video Answer


1 Answers

Use itertools.cycle to cycle around to the beginning of L2:

from itertools import cycle dict(zip(L1, cycle(L2))) # {'A': '1', 'B': '2', 'C': '3', 'D': '1', 'E': '2'} 

In your case, concatenating L2 with itself also works.

# dict(zip(L1, L2 * 2)) dict(zip(L1, L2 + L2)) # {'A': '1', 'B': '2', 'C': '3', 'D': '1', 'E': '2'} 
like image 84
cs95 Avatar answered Sep 21 '22 14:09

cs95