Dictionaries

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Lad

    #1

    Dictionaries

    How can I add two dictionaries into one?
    E.g.
    a={'a:1}
    b={'b':2}

    I need

    the result {'a':1,'b':2}.

    Is it possible?

    Thank you
    L.

  • Simon Brunning

    #2
    Re: Dictionaries

    On 18 Oct 2006 08:24:27 -0700, Lad <python@hope.cz wrote:
    How can I add two dictionaries into one?
    E.g.
    a={'a:1}
    b={'b':2}
    >
    I need
    >
    the result {'a':1,'b':2}.
    >>a={'a':1}
    >>b={'b':2}
    >>a.update(b)
    >>a
    {'a': 1, 'b': 2}

    --
    Cheers,
    Simon B
    simon@brunningo nline.net

    Comment

    • Gary Herron

      #3
      Re: Dictionaries

      Lad wrote:
      How can I add two dictionaries into one?
      E.g.
      a={'a:1}
      b={'b':2}
      >
      I need
      >
      the result {'a':1,'b':2}.
      >
      Is it possible?
      >
      Thank you
      L.
      >
      >
      Yes, use update. Beware that this modifies a dictionary in place rather
      than returning a new dictionary.
      >>a={'a':1}
      >>b={'b':2}
      >>a.update(b)
      >>a
      {'a': 1, 'b': 2}

      Gary Herron


      Comment

      • Tim Chase

        #4
        Re: Dictionaries

        How can I add two dictionaries into one?
        E.g.
        a={'a:1}
        b={'b':2}
        >
        I need
        >
        the result {'a':1,'b':2}.
        >>a.update(b)
        >>a
        {'a':1,'b':2}

        -tkc


        Comment

        • Boris Borcic

          #5
          Re: Dictionaries


          dict(a.items() + b.items())

          Lad wrote:
          How can I add two dictionaries into one?
          E.g.
          a={'a:1}
          b={'b':2}
          >
          I need
          >
          the result {'a':1,'b':2}.
          >
          Is it possible?

          Comment

          • Steven D'Aprano

            #6
            Re: Dictionaries

            On Wed, 18 Oct 2006 08:24:27 -0700, Lad wrote:
            How can I add two dictionaries into one?
            E.g.
            a={'a:1}
            b={'b':2}
            >
            I need
            >
            the result {'a':1,'b':2}.
            >
            Is it possible?
            What should the result be if both dictionaries have the same key?

            a={'a':1, 'b'=2}
            b={'b':3}

            should the result be:
            {'a':1, 'b'=2} # keep the existing value
            {'a':1, 'b'=3} # replace the existing value
            {'a':1, 'b'=[2, 3]} # keep both values
            or something else?

            Other people have already suggested using the update() method. If you want
            more control, you can do something like this:

            def add_dict(A, B):
            """Add dictionaries A and B and return a new dictionary."""
            C = A.copy() # start with a copy of A
            for key, value in B.items():
            if C.has_key(key):
            raise ValueError("dup licate key '%s' detected!" % key)
            C[key] = value
            return C


            --
            Steven.

            Comment

            • Lad

              #7
              Re: Dictionaries


              Tim Chase wrote:
              How can I add two dictionaries into one?
              E.g.
              a={'a:1}
              b={'b':2}

              I need

              the result {'a':1,'b':2}.
              >
              >>a.update(b)
              >>a
              {'a':1,'b':2}
              >
              -tkc
              Thank you ALL for help.
              However It does not work as I would need.
              Let's suppose I have

              a={'c':1,'d':2}
              b={'c':2}
              but
              a.update(b)
              will make
              {'c': 2, 'd': 2}

              and I would need
              {'c': 3, 'd': 2}

              (because `c` is 1 in `a` dictionary and `c` is 2 in `b` dictionary, so
              1+2=3)

              How can be done that?
              Thank you for the reply
              L

              Comment

              • Tim Chase

                #8
                Re: Dictionaries

                However It does not work as I would need.
                Let's suppose I have
                >
                a={'c':1,'d':2}
                b={'c':2}
                but
                a.update(b)
                will make
                {'c': 2, 'd': 2}
                >
                and I would need
                {'c': 3, 'd': 2}
                Ah...a previously omitted detail.

                There are likely a multitude of ways to do it. However, the one
                that occurs to me off the top of my head would be something like

                dict((k, a.get(k, 0) + b.get(k, 0)) for k in a.keys()+b.keys ())


                If the sets are huge, you can use itertools
                >>from itertools import chain
                >>dict((k, a.get(k, 0) + b.get(k, 0)) for k in
                chain(a.keys(), b.keys()))
                {'c': 3, 'd': 2}

                which would reduce the need for creating the combined dictionary,
                only to throw it away.

                -tkc





                Comment

                • Lad

                  #9
                  Re: Dictionaries


                  Steven,
                  Thank you for your reply and question.
                  >
                  What should the result be if both dictionaries have the same key?
                  The answer: the values should be added together and assigned to the key
                  That is
                  {'a':1, 'b':5}
                  ( from your example below)

                  Is there a solution?
                  Thanks for the reply
                  L.
                  >
                  a={'a':1, 'b'=2}
                  b={'b':3}
                  >
                  should the result be:
                  {'a':1, 'b'=2} # keep the existing value
                  {'a':1, 'b'=3} # replace the existing value
                  {'a':1, 'b'=[2, 3]} # keep both values
                  or something else?
                  >
                  Other people have already suggested using the update() method. If you want
                  more control, you can do something like this:
                  >
                  def add_dict(A, B):
                  """Add dictionaries A and B and return a new dictionary."""
                  C = A.copy() # start with a copy of A
                  for key, value in B.items():
                  if C.has_key(key):
                  raise ValueError("dup licate key '%s' detected!" % key)
                  C[key] = value
                  return C
                  >
                  >
                  --
                  Steven.

                  Comment

                  • Rob De Almeida

                    #10
                    Re: Dictionaries

                    Lad wrote:
                    Let's suppose I have
                    >
                    a={'c':1,'d':2}
                    b={'c':2}
                    but
                    a.update(b)
                    will make
                    {'c': 2, 'd': 2}
                    >
                    and I would need
                    {'c': 3, 'd': 2}
                    >
                    (because `c` is 1 in `a` dictionary and `c` is 2 in `b` dictionary, so
                    1+2=3)
                    >
                    How can be done that?
                    dict([(k, a.get(k, 0) + b.get(k,0)) for k in set(a.keys() + b.keys())])

                    Comment

                    • Fredrik Lundh

                      #11
                      Re: Dictionaries

                      Lad wrote:
                      The answer: the values should be added together and assigned to the key
                      That is
                      {'a':1, 'b':5}
                      ( from your example below)
                      >
                      Is there a solution?
                      have you tried coding a solution and failed, or are you just expecting
                      people to code for free?

                      </F>

                      Comment

                      • Steven D'Aprano

                        #12
                        Re: Dictionaries

                        On Wed, 18 Oct 2006 09:31:50 -0700, Lad wrote:
                        >
                        Steven,
                        Thank you for your reply and question.
                        >
                        >>
                        >What should the result be if both dictionaries have the same key?
                        The answer: the values should be added together and assigned to the key
                        That is
                        {'a':1, 'b':5}
                        ( from your example below)
                        >
                        Is there a solution?
                        Of course there is a solution. You just have to program it.

                        Look again at my example code before:

                        def add_dict(A, B):
                        """Add dictionaries A and B and return a new dictionary."""
                        C = A.copy() # start with a copy of A
                        for key, value in B.items():
                        if C.has_key(key):
                        raise ValueError("dup licate key '%s' detected!" % key)
                        C[key] = value
                        return C


                        Can you see how to modify this function to do what you want?

                        (Hint: instead of raising a ValueError exception, you want to do something
                        else.)


                        --
                        Steven.

                        Comment

                        • Gary Herron

                          #13
                          Re: Dictionaries

                          Fredrik Lundh wrote:
                          Lad wrote:
                          >
                          >
                          >The answer: the values should be added together and assigned to the key
                          >That is
                          >{'a':1, 'b':5}
                          >( from your example below)
                          >>
                          >Is there a solution?
                          >>
                          >
                          have you tried coding a solution and failed, or are you just expecting
                          people to code for free?
                          >
                          </F>
                          >
                          >
                          Right. This thread begins to look like someone with a homework
                          assignment asking for code rather than attempting to try programming it
                          up himself. I was happy to answer the first plea for help, but I'd be
                          leery of providing any actual code.

                          Gary Herron

                          Comment

                          • Lad

                            #14
                            Re: Dictionaries

                            Steven,
                            Thank you for help;
                            Here is a code that works in a way I need


                            A={'c':1,'d':2, 'e':3,'f':2}
                            B={'c':2,'e':1}
                            if len(A)>=len(B):
                            Delsi=B
                            C = A.copy()
                            else:
                            Delsi=A
                            C = B.copy()

                            for key, value in Delsi.items():
                            if C.has_key(key):
                            C[key]=C[key]+value
                            else:
                            C[key]=value



                            How easy :-)
                            Regards,
                            L.

                            Steven D'Aprano wrote:
                            On Wed, 18 Oct 2006 09:31:50 -0700, Lad wrote:
                            >

                            Steven,
                            Thank you for your reply and question.
                            >
                            What should the result be if both dictionaries have the same key?
                            The answer: the values should be added together and assigned to the key
                            That is
                            {'a':1, 'b':5}
                            ( from your example below)

                            Is there a solution?
                            >
                            Of course there is a solution. You just have to program it.
                            >
                            Look again at my example code before:
                            >
                            def add_dict(A, B):
                            """Add dictionaries A and B and return a new dictionary."""
                            C = A.copy() # start with a copy of A
                            for key, value in B.items():
                            if C.has_key(key):
                            raise ValueError("dup licate key '%s' detected!" % key)
                            C[key] = value
                            return C
                            >
                            >
                            Can you see how to modify this function to do what you want?
                            >
                            (Hint: instead of raising a ValueError exception, you want to do something
                            else.)
                            >
                            >
                            --
                            Steven.

                            Comment

                            Working...