-2

I have 2 dictionaries like:

d1 = { 'AAPL' : [1, 2, 3] , 'MSFT' : [3, 4, 5] }

d2 = {1 : [], 2 : [], 3 : [], 4 : [], 5 : []} 

and I need 1 dictionary like:

d3 = {1 : ['AAPL'], 2 : ['AAPL'], 3 : ['AAPL', 'MSFT'], 4 : ['MSFT'], 5 : ['MSFT']}  

How do I get d3?

Mustafa Aydın
  • 17,645
  • 4
  • 15
  • 38
  • 2
    You didnt post your attempt code to do it. pls read this https://stackoverflow.com/help/how-to-ask – Wonka May 07 '21 at 09:04
  • 1
    StackOverlow isn't a code-writing service; please edit your honest attempt to code this into your question as a [mre] - include all information (including data) needed so anyone can paste your code into a file and _without adding anything_ run it to see the same problem you're having. – DisappointedByUnaccountableMod May 07 '21 at 09:06
  • I am sorry, I am new to StackOverflow and I take your comments into consideration for my next question. Thanks! – mick_stackaccount May 07 '21 at 09:54
  • @mick_stackaccount check this out https://stackoverflow.com/questions/38987/how-do-i-merge-two-dictionaries-in-a-single-expression-taking-union-of-dictiona – user1538798 May 07 '21 at 11:09

2 Answers2

1

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.

Synthase
  • 5,849
  • 2
  • 12
  • 34
1

A collections.defaultdict will do it nicely

d1 = {'AAPL': [1, 2, 3], 'MSFT': [3, 4, 5]}

result = defaultdict(list)
for k, v in d1.items():
    for x in v:
        result[x].append(k)

print(result)
# {1: ['AAPL'], 2: ['AAPL'], 3: ['AAPL', 'MSFT'], 4: ['MSFT'], 5: ['MSFT']}
azro
  • 53,056
  • 7
  • 34
  • 70