How to say $a=$b->{"A"} ||={} in Python?

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

    How to say $a=$b->{"A"} ||={} in Python?

    Hi All.

    I'd like to do the following in more succint code:

    if k in b:
    a=b[k]
    else:
    a={}
    b[k]=a

    a['A']=1


    In perl it is just one line: $a=$b->{"A"} ||={}.

    Thanks,
    Geoffrey

  • Lawrence Oluyede

    #2
    Re: How to say $a=$b->{"A&qu ot;} ||={} in Python?

    beginner <zyzhu2000@gmai l.comwrote:
    I'd like to do the following in more succint code:
    >
    if k in b:
    a=b[k]
    else:
    a={}
    b[k]=a
    b.setdefault(k, a)

    --
    Lawrence, oluyede.org - neropercaso.it
    "It is difficult to get a man to understand
    something when his salary depends on not
    understanding it" - Upton Sinclair

    Comment

    • beginner

      #3
      Re: How to say $a=$b-&gt;{&quot;A&qu ot;} ||={} in Python?

      On Aug 16, 5:43 pm, ra...@dot.com (Lawrence Oluyede) wrote:
      beginner <zyzhu2...@gmai l.comwrote:
      I'd like to do the following in more succint code:
      >
      if k in b:
      a=b[k]
      else:
      a={}
      b[k]=a
      >
      b.setdefault(k, a)
      >
      --
      Lawrence, oluyede.org - neropercaso.it
      "It is difficult to get a man to understand
      something when his salary depends on not
      understanding it" - Upton Sinclair
      I am afraid it is not the same. b.setdefault(k, {}) will always create
      an empty dict, even if k is in b, as demonstrated in the below code.

      b={}
      def f(i):
      print "I am evaluated %d" % i
      return i

      b.setdefault('A ', f(1))
      b.setdefault('A ', f(2))
      b


      Comment

      • Carl Banks

        #4
        Re: How to say $a=$b-&gt;{&quot;A&qu ot;} ||={} in Python?

        On Aug 16, 6:35 pm, beginner <zyzhu2...@gmai l.comwrote:
        Hi All.
        >
        I'd like to do the following in more succint code:
        >
        if k in b:
        a=b[k]
        else:
        a={}
        b[k]=a
        >
        a['A']=1
        >
        In perl it is just one line: $a=$b->{"A"} ||={}.
        >
        Thanks,
        Geoffrey
        Define b as a default dict:

        b = defaultdict(dic t)
        b[k]['A'] = l



        Carl Banks

        Comment

        • Jonathan Gardner

          #5
          Re: How to say $a=$b-&gt;{&quot;A&qu ot;} ||={} in Python?

          On Aug 16, 3:35 pm, beginner <zyzhu2...@gmai l.comwrote:
          >
          In perl it is just one line: $a=$b->{"A"} ||={}.
          >
          a = b.setdefault('A ', {})

          This combines all two actions together:
          - Sets b['A'] to {} if it is not already defined
          - Assigns b['A'] to a

          More info on dict methods here:



          Comment

          • Paul McGuire

            #6
            Re: How to say $a=$b-&gt;{&quot;A&qu ot;} ||={} in Python?

            On Aug 16, 8:28 pm, Jonathan Gardner
            <jgardner.jonat hangardner....@ gmail.comwrote:
            On Aug 16, 3:35 pm, beginner <zyzhu2...@gmai l.comwrote:
            >
            >
            >
            In perl it is just one line: $a=$b->{"A"} ||={}.
            >
            a = b.setdefault('A ', {})
            >
            This combines all two actions together:
            - Sets b['A'] to {} if it is not already defined
            - Assigns b['A'] to a
            >
            More info on dict methods here:
            >
            http://docs.python.org/lib/typesmapping.html
            No, this has already been proposed and discarded. The OP does NOT
            want this, because it always generates an empty {} whether it is
            needed or not. Not really a big hardship, but if the default value
            were some expensive-to-construct container class, then you would be
            creating one every time you wanted to reference a value, on the chance
            that the key did not exist.

            Carl Banks' post using defaultdict is the correct solution. The
            raison d'etre for defaultdict, and the reason that it is the solution
            to the OP's question, is that instead of creating a just-in-case
            default value every time, the defaultdict itself is constructed with a
            factory method of some kind (in practice, it appears that this factory
            method is usually the list or dict class constructor). If a reference
            to the defaultdict gives a not-yet-existing key, then the factory
            method is called to construct the new value, that value is stored in
            the dict with the given key, and the value is passed back to the
            caller. No instances are created unless they are truly required for
            initializing an entry for a never-before-seen key.

            -- Paul

            Comment

            • Paul McGuire

              #7
              Re: How to say $a=$b-&gt;{&quot;A&qu ot;} ||={} in Python?

              On Aug 16, 6:03 pm, Carl Banks <pavlovevide... @gmail.comwrote :
              On Aug 16, 6:35 pm, beginner <zyzhu2...@gmai l.comwrote:
              >
              Hi All.
              >
              I'd like to do the following in more succint code:
              >
              if k in b:
              a=b[k]
              else:
              a={}
              b[k]=a
              >
              a['A']=1
              >
              In perl it is just one line: $a=$b->{"A"} ||={}.
              >
              Thanks,
              Geoffrey
              >
              Define b as a default dict:
              >
              b = defaultdict(dic t)
              b[k]['A'] = l
              >
              Carl Banks- Hide quoted text -
              >
              - Show quoted text -
              I think the most direct translation of the OP's example to Python
              would be:

              # setup b as special flavor of dict, that creates a
              # new dict for not-yet-created keys
              b = defaultdict(dic t)

              # actual python impl of $a=$b->{k}||={}
              a = b[k]

              # assign 1 to retrieved/created dict
              a['A'] = 1

              -- Paul

              Comment

              • Carsten Haese

                #8
                Re: How to say $a=$b-&gt;{&quot;A&qu ot;} ||={} in Python?

                On Fri, 2007-08-17 at 00:53 +0000, beginner wrote:
                $b is supposed to be a hash-table of hash-table. If a key exists in
                $b, it points to another hash table. The $a=$b->{"A"} ||={} pattern is
                useful when you want to add records to the double hash table.
                >
                For example, if you have a series of records in the format of (K1, K2,
                V), and you want to add them to the double hash-table, you can do
                $a=$b->{K1} || ={}
                $a->{K2}=V
                What is the best solution in Perl need not be the best solution in
                Python. In Python you should just use a tuple as your dict key, i.e.
                a[k1,k2] = v, unless you have some other constraints you're not telling
                us.

                HTH,

                --
                Carsten Haese



                Comment

                • beginner

                  #9
                  Re: How to say $a=$b-&gt;{&quot;A&qu ot;} ||={} in Python?

                  On Aug 16, 9:32 pm, Carsten Haese <cars...@uniqsy s.comwrote:
                  On Fri, 2007-08-17 at 00:53 +0000, beginner wrote:
                  $b is supposed to be a hash-table of hash-table. If a key exists in
                  $b, it points to another hash table. The $a=$b->{"A"} ||={} pattern is
                  useful when you want to add records to the double hash table.
                  >
                  For example, if you have a series of records in the format of (K1, K2,
                  V), and you want to add them to the double hash-table, you can do
                  $a=$b->{K1} || ={}
                  $a->{K2}=V
                  >
                  What is the best solution in Perl need not be the best solution in
                  Python. In Python you should just use a tuple as your dict key, i.e.
                  a[k1,k2] = v, unless you have some other constraints you're not telling
                  us.
                  >
                  HTH,
                  >
                  --
                  Carsten Haesehttp://informixdb.sour ceforge.net
                  I use tuples this way all the time. It is indeed very neat. But it is
                  not a replacement for double hash-table. If I want to retrieve
                  information just by K1, it is not efficient to index on (K1, K2).

                  Comment

                  • beginner

                    #10
                    Re: How to say $a=$b-&gt;{&quot;A&qu ot;} ||={} in Python?

                    On Aug 16, 5:35 pm, beginner <zyzhu2...@gmai l.comwrote:
                    Hi All.
                    >
                    I'd like to do the following in more succint code:
                    >
                    if k in b:
                    a=b[k]
                    else:
                    a={}
                    b[k]=a
                    >
                    a['A']=1
                    >
                    In perl it is just one line: $a=$b->{"A"} ||={}.
                    >
                    Thanks,
                    Geoffrey
                    It looks like defaultdict is the solution for this kind of thing.
                    Thanks all for your help.

                    Comment

                    • Carsten Haese

                      #11
                      Re: How to say $a=$b-&gt;{&quot;A&qu ot;} ||={} in Python?

                      On Fri, 17 Aug 2007 03:15:10 -0000, beginner wrote
                      On Aug 16, 9:32 pm, Carsten Haese <cars...@uniqsy s.comwrote:
                      What is the best solution in Perl need not be the best solution in
                      Python. In Python you should just use a tuple as your dict key, i.e.
                      a[k1,k2] = v, unless you have some other constraints you're not telling
                      us.

                      HTH,

                      --
                      Carsten Haesehttp://informixdb.sour ceforge.net
                      >
                      I use tuples this way all the time. It is indeed very neat. But it
                      is not a replacement for double hash-table. If I want to retrieve
                      information just by K1, it is not efficient to index on (K1, K2).
                      If you have to look up all values associates with k1 and any k2, you're right,
                      that's not efficient. That would fall under "other constraints you're not
                      telling us." I'm not a mind reader.

                      -Carsten

                      Comment

                      • =?ISO-8859-1?Q?S=E9bastien_Buchoux?=

                        #12
                        Re: How to say $a=$b-&gt;{&quot;A&qu ot;} ||={} in Python?

                        beginner a écrit :
                        Hi All.
                        >
                        I'd like to do the following in more succint code:
                        >
                        if k in b:
                        a=b[k]
                        else:
                        a={}
                        b[k]=a
                        >
                        a['A']=1
                        >
                        >
                        In perl it is just one line: $a=$b->{"A"} ||={}.
                        >
                        Thanks,
                        Geoffrey
                        >
                        >
                        One solution I often use in such cases:

                        try:
                        a = b[k]
                        except KeyError: #or except IndexError: if b is a list/tuple and not a dict
                        a = {}
                        b[k] = a

                        a['A'] = 1

                        Indeed, exceptions are handled faster than "if/else" loops. As it was
                        mentionned earlier, One neat solution in Perl may not be the perfect one
                        in Python.

                        Cheers,

                        Sébastien

                        Comment

                        • beginner

                          #13
                          Re: How to say $a=$b-&gt;{&quot;A&qu ot;} ||={} in Python?

                          On Aug 17, 2:35 am, Sébastien Buchoux <seb.buch...@gm ail.comwrote:
                          beginner a écrit :
                          >
                          >
                          >
                          Hi All.
                          >
                          I'd like to do the following in more succint code:
                          >
                          if k in b:
                          a=b[k]
                          else:
                          a={}
                          b[k]=a
                          >
                          a['A']=1
                          >
                          In perl it is just one line: $a=$b->{"A"} ||={}.
                          >
                          Thanks,
                          Geoffrey
                          >
                          One solution I often use in such cases:
                          >
                          try:
                          a = b[k]
                          except KeyError: #or except IndexError: if b is a list/tuple and not a dict
                          a = {}
                          b[k] = a
                          >
                          a['A'] = 1
                          >
                          Indeed, exceptions are handled faster than "if/else" loops. As it was
                          mentionned earlier, One neat solution in Perl may not be the perfect one
                          in Python.
                          >
                          Cheers,
                          >
                          Sébastien- Hide quoted text -
                          >
                          - Show quoted text -
                          Wow. This solution is interesting. I'll try this. Thanks.

                          Comment

                          • beginner

                            #14
                            Re: How to say $a=$b-&gt;{&quot;A&qu ot;} ||={} in Python?

                            On Aug 16, 11:02 pm, "Carsten Haese" <cars...@uniqsy s.comwrote:
                            On Fri, 17 Aug 2007 03:15:10 -0000, beginner wrote
                            >
                            On Aug 16, 9:32 pm, Carsten Haese <cars...@uniqsy s.comwrote:
                            What is the best solution in Perl need not be the best solution in
                            Python. In Python you should just use a tuple as your dict key, i.e.
                            a[k1,k2] = v, unless you have some other constraints you're not telling
                            us.
                            >
                            HTH,
                            >
                            --
                            Carsten Haesehttp://informixdb.sour ceforge.net
                            >
                            I use tuples this way all the time. It is indeed very neat. But it
                            is not a replacement for double hash-table. If I want to retrieve
                            information just by K1, it is not efficient to index on (K1, K2).
                            >
                            If you have to look up all values associates with k1 and any k2, you're right,
                            that's not efficient. That would fall under "other constraints you're not
                            telling us." I'm not a mind reader.
                            >
                            -Carsten
                            Yeah, I should have mentioned that I actually want to group the data
                            by K1 and then by K2.

                            Comment

                            • Carl Banks

                              #15
                              Re: How to say $a=$b-&gt;{&quot;A&qu ot;} ||={} in Python?

                              On Aug 16, 10:01 pm, Paul McGuire <pt...@austin.r r.comwrote:
                              On Aug 16, 8:28 pm, Jonathan Gardner
                              >
                              >
                              >
                              <jgardner.jonat hangardner....@ gmail.comwrote:
                              On Aug 16, 3:35 pm, beginner <zyzhu2...@gmai l.comwrote:
                              >
                              In perl it is just one line: $a=$b->{"A"} ||={}.
                              >
                              a = b.setdefault('A ', {})
                              >
                              This combines all two actions together:
                              - Sets b['A'] to {} if it is not already defined
                              - Assigns b['A'] to a
                              >
                              More info on dict methods here:
                              >>
                              No, this has already been proposed and discarded. The OP does NOT
                              want this, because it always generates an empty {} whether it is
                              needed or not. Not really a big hardship, but if the default value
                              were some expensive-to-construct container class, then you would be
                              creating one every time you wanted to reference a value, on the chance
                              that the key did not exist.
                              >
                              Carl Banks' post using defaultdict is the correct solution. The
                              raison d'etre for defaultdict, and the reason that it is the solution
                              to the OP's question, is that instead of creating a just-in-case
                              default value every time, the defaultdict itself is constructed with a
                              factory method of some kind (in practice, it appears that this factory
                              method is usually the list or dict class constructor). If a reference
                              to the defaultdict gives a not-yet-existing key, then the factory
                              method is called to construct the new value, that value is stored in
                              the dict with the given key, and the value is passed back to the
                              caller. No instances are created unless they are truly required for
                              initializing an entry for a never-before-seen key.

                              When I made my response, it occurred to me that Python could be
                              improved (maybe) if one could overload dict.get() to use a factory,
                              like so:

                              b = {}
                              a = b.get(k,factory =dict)
                              a['A'] = 1

                              That's a slight improvement (maybe) over defaultdict since it would
                              still allow the same dict to have the membership check in other
                              places. I'm not so sure overloading get to let it modify the dict is
                              a good idea, though.

                              Actually, it'd probably be fairly uncontroversial to add a factory
                              keyword to dict.setdefault (). At least insofar as setdefault is
                              uncontroversial .


                              Carl Banks

                              Comment

                              Working...