Connecting Tech Pros Worldwide Help | Site Map

merging dictionaries

Newbie
 
Join Date: Feb 2009
Posts: 31
#1: Mar 12 '09
so basically i've written most of the code the only problem that i'm having is that the output that it gives me will not return a key with a different type. It will either return me keys with only int, or only str..for example

Expand|Select|Wrap|Line Numbers
  1. def merge_dictionaries(d1, d2):
  2.     '''Return a dictionary that is the result of merging the two given 
  3.     dictionaries. In the new dictionary, the values should be lists. If a key 
  4.     is in both of the given dictionaries, the value in the new dictionary should
  5.     contain both of the values from the given dictionaries, even if they are the 
  6.     same. '''
  7.  
  8.     d3 = {}
  9.     for c in d1:
  10.         if c in d2:
  11.             d3[c] = [d1[c], d2[c]]
  12.         else:
  13.             d3[c] = [d1[c]]
  14.     print d3
  15.  
how i tested it is with:

Expand|Select|Wrap|Line Numbers
  1. merge_dictionaries({ 1 : 'a', 2 : 9, -8 : 'w'}, {2 : 7, 'x' : 3, 1 : 'a'})
  2.  
and the out put is:
Expand|Select|Wrap|Line Numbers
  1. {-8: ['w'], 1: ['a', 'a'], 2: [9, 7]}
why doesn't it print out the 'x' key and value??
bvdet's Avatar
Moderator
 
Join Date: Oct 2006
Location: Nashville, TN
Posts: 1,560
#2: Mar 13 '09

re: merging dictionaries


Because d2 has a key that d1 does not have. You only iterate on d1, so key 'x' is never seen.

-BV
bvdet's Avatar
Moderator
 
Join Date: Oct 2006
Location: Nashville, TN
Posts: 1,560
#3: Mar 13 '09

re: merging dictionaries


Take a look at this:
Expand|Select|Wrap|Line Numbers
  1. import copy
  2.  
  3. def merge_dictionaries(d1, d2):
  4.     d3 = copy.copy(d1)
  5.     for key in d2:
  6.         if key in d3:
  7.             d3[key] = [d3[key], d2[key]]
  8.         else:
  9.             d3[key] = [d2[key]]
  10.     return d3
  11.  
  12. dd1 = { 1 : 'a', 2 : 9, -8 : 'w'}
  13. dd2 = {2 : 7, 'x' : 3, 1 : 'a'}
  14. print merge_dictionaries(dd1, dd2)
Newbie
 
Join Date: Feb 2009
Posts: 31
#4: Mar 13 '09

re: merging dictionaries


in this case you imported copy, what is that?
bvdet's Avatar
Moderator
 
Join Date: Oct 2006
Location: Nashville, TN
Posts: 1,560
#5: Mar 13 '09

re: merging dictionaries


Quote:

Originally Posted by v13tn1g View Post

in this case you imported copy, what is that?

copy.copy makes a shallow copy of an object. From Python documentation:
"A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original."

This will do the same thing:
Expand|Select|Wrap|Line Numbers
  1. d3 = dict(d1.items())
Reply