From these lists,
lst1 = ['a','b','c']
lst2 = [[1,2],[3,4,5],[6,7]]
I want to create:
{1: 'a', 3: 'b', 6: 'c', 2: 'a', 4: 'b', 7: 'c', 5: 'b'}
I can create it using a for loop:
d = {}
for l, nums in zip(lst1, lst2):
for num in nums:
d[num] = l
I figured I need to use map and zip, so I tried,
dict(map(lambda x: dict(x), zip(lst2,lst1)))
but this gives
ValueError: dictionary update sequence element #1 has length 1; 2 is required.
I think the issue is the lst2
is a list of lists but I just don't know how to proceed.
EDIT:
Your expected output is different from the output produced by your loop. If you want to get the expected output in a one liner (excluding imports of course), here is one solution.
(i) Building on @mozway's idea of using
itertools.zip_longest
to create zip object of tuples across sublists, usedict.fromkeys
method to create a dictionary from these tuples andlst1
,(ii) Using
map
and a dict comprehension, create a list of dictionaries from (i)(iii) Using
functools.reduce
, flatten the list to a single dictionaryAnother solution:
Output:
Old solution (if order doesn't matter):
As you say, the issue is that
lst1
is a list andlst2
is a list of lists. We can use another zip to create sublists fromlst1
. Then usefunctools.reduce
to flatten the list of dictionaries:Or using @Tadhg's excellent suggestion to use
itertools.starmap
anddict.fromkeys
methods, you can also do:or using
collections.ChainMap
(even simpler):Output: