merging dictionaries

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • v13tn1g
    New Member
    • Feb 2009
    • 31

    merging dictionaries

    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

    Code:
    def merge_dictionaries(d1, d2):
        '''Return a dictionary that is the result of merging the two given 
        dictionaries. In the new dictionary, the values should be lists. If a key 
        is in both of the given dictionaries, the value in the new dictionary should
        contain both of the values from the given dictionaries, even if they are the 
        same. '''
        
        d3 = {}
        for c in d1:
            if c in d2:
                d3[c] = [d1[c], d2[c]]
            else:
                d3[c] = [d1[c]]
        print d3
    how i tested it is with:

    Code:
    merge_dictionaries({ 1 : 'a', 2 : 9, -8 : 'w'}, {2 : 7, 'x' : 3, 1 : 'a'})
    and the out put is:
    Code:
    {-8: ['w'], 1: ['a', 'a'], 2: [9, 7]}
    why doesn't it print out the 'x' key and value??
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

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

    -BV

    Comment

    • bvdet
      Recognized Expert Specialist
      • Oct 2006
      • 2851

      #3
      Take a look at this:
      Code:
      import copy
      
      def merge_dictionaries(d1, d2):
          d3 = copy.copy(d1)
          for key in d2:
              if key in d3:
                  d3[key] = [d3[key], d2[key]]
              else:
                  d3[key] = [d2[key]]
          return d3
      
      dd1 = { 1 : 'a', 2 : 9, -8 : 'w'}
      dd2 = {2 : 7, 'x' : 3, 1 : 'a'}
      print merge_dictionaries(dd1, dd2)

      Comment

      • v13tn1g
        New Member
        • Feb 2009
        • 31

        #4
        in this case you imported copy, what is that?

        Comment

        • bvdet
          Recognized Expert Specialist
          • Oct 2006
          • 2851

          #5
          Originally posted by v13tn1g
          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:
          Code:
          d3 = dict(d1.items())

          Comment

          Working...