Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 Combining two dictionaries into one.
Index -> Programming, Python -> Python Help
View previous topic Printable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh pageAdd this topic to your bookmarks (CTRL-D) View next topic
Author Message
implosion




PostPosted: 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
 
Sponsor
Sponsor
Sponsor
sponsor
The_Bean




PostPosted: 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.



projection.PNG
 Description:
projection
 Filesize:  15.51 KB
 Viewed:  226 Time(s)

projection.PNG


 
implosion




PostPosted: 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

 
Display posts from previous:   
   Index -> Programming, Python -> Python Help
View previous topic Tell A FriendPrintable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh pageAdd this topic to your bookmarks (CTRL-D) View next topic

Page 1 of 1  [ 3 Posts ]
Jump to:   


Style:  
Search: