In your example your dictionary d2
is useless. Still:
d1 = { 'AAPL' : [1, 2, 3] , 'MSFT' : [3, 4, 5] }
#d2 = {1 : [], 2 : [], 3 : [], 4 : [], 5 : []}
d3 = {}
for v in d1.values():
for k in v:
d3[k] = []
for k,v in d1.items():
for x in v:
d3[x].append(k)
print (d3)
Output:
{1: ['AAPL'], 2: ['AAPL'], 3: ['AAPL', 'MSFT'], 4: ['MSFT'], 5: ['MSFT']}
You can also do:
for k,v in d1.items():
for x in v:
if x not in d3.keys():
d3[x] = []
d3[x].append(k)
print (d3)
Here instead of doing the same loop twice (once to init, the other to fill), you test if your key exists or not and proceed accordingly.