Computer Science Canada

Combining two dictionaries into one.

Author:  implosion [ Sat Nov 07, 2009 4:35 pm ]
Post subject:  Combining two dictionaries into one.

Here is the question..

Given dictionaries, d1 and d2, create a new dictionary with the following property: for each entry (a, b) in d1, if there is an entry (b, c) in d2, then the entry (a, c) should be added to the new dictionary.

For example, if d1 is {2:3, 8:19, 6:4, 5:12} and d2 is {2:5, 4:3, 3:9}, then the new dictionary should be {2:9, 6:3}
Associate the new dictionary with the variable d3

I don't really understand the question, but this is my attempt at it so far...

code:
d1 = {2:3, 8:19, 6:4, 5:12}
d2 = {2:5, 4:3, 3:9}
d3 = {}
for k in d1:
    if d2.has_key(d1[k]):
        d3 [k] = d2[k]
       
print d3

Author:  The_Bean [ Sat Nov 07, 2009 7:30 pm ]
Post subject:  Re: Combining two dictionaries into one.

Your really close to having it work, your just assigning d3's keys the wrong value.

Here's a picture to help explain it.

Author:  implosion [ Sat Nov 07, 2009 8:47 pm ]
Post subject:  Re: Combining two dictionaries into one.

thanks for the visual! .. i kept trying to look for a built in function/method but i couldn't find one. simpler once i saw the diagram.

code:
d1 = {2:3, 8:19, 6:4, 5:12}
d2 = {2:5, 4:3, 3:9}
d3 = {}
for k in d1:
    if d2.has_key(d1[k]):
        d3 [k] = d2[d1[k]]   
print d3



: