Create dictionary based of x items per key from two lists

Ian Kelly ian.g.kelly at gmail.com
Sun Feb 1 13:51:55 EST 2015


On Sat, Jan 31, 2015 at 7:38 PM, Jason Friedman <jsf80238 at gmail.com> wrote:
>> I have two lists
>>
>> l1 =  ["a","b","c","d","e","f","g","h","i","j"]
>> l2 = ["aR","bR","cR"]
>>
>> l2 will always be smaller or equal to l1
>>
>> numL1PerL2 = len(l1)/len(l2)
>>
>> I want to create a dictionary that has key from l1 and value from l2 based on numL1PerL2
>>
>> So
>>
>> {
>> a:aR,
>> b:aR,
>> c:aR,
>> d:bR,
>> e:bR,
>> f:bR,
>> g:cR,
>> h:cR,
>> i:cR,
>> j:cR
>> }
>
> Another possibility is:
> import itertools
> my_dict = {x:y for x,y in zip(list1, itertools.cycle(list2))}

That results in a different mapping than the one specified by the OP,
though. An alternate itertools approach could be:

dict(zip_longest(l1, chain.from_iterable(
    map(partial(repeat, times=len(l1) // len(l2)), l2)), fillvalue=l2[-1]))

although this requires the inputs to be sequences, not arbitrary iterables.



More information about the Python-list mailing list