Syntax for extracting multiple items from a dictionary

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

    #1

    Syntax for extracting multiple items from a dictionary

    row = {"fname" : "Frank", "lname" : "Jones", "city" : "Hoboken", "state" :
    "Alaska"}
    cols = ("city", "state")

    Is there a best-practices way to ask for an object containing only the keys
    named in cols out of row? In other words, to get this:
    {"city" : "Hoboken", "state" : "Alaska"}

    Thanks,

    shark


  • Leif K-Brooks

    #2
    Re: Syntax for extracting multiple items from a dictionary

    shark wrote:[color=blue]
    > row = {"fname" : "Frank", "lname" : "Jones", "city" : "Hoboken", "state" :
    > "Alaska"}
    > cols = ("city", "state")
    >
    > Is there a best-practices way to ask for an object containing only the keys
    > named in cols out of row? In other words, to get this:
    > {"city" : "Hoboken", "state" : "Alaska"}[/color]

    Why would you need to do that? There's nothing you can do to the second
    dictionary that you can't do to the first, so what's wrong with leaving
    the extra items in place?

    Comment

    • Roy Smith

      #3
      Re: Syntax for extracting multiple items from a dictionary

      In article <TuednaLvv_626T HcRVn-hA@rcn.net>, "shark" <no@spam.none >
      wrote:
      [color=blue]
      > row = {"fname" : "Frank", "lname" : "Jones", "city" : "Hoboken", "state" :
      > "Alaska"}
      > cols = ("city", "state")
      >
      > Is there a best-practices way to ask for an object containing only the keys
      > named in cols out of row? In other words, to get this:
      > {"city" : "Hoboken", "state" : "Alaska"}
      >
      > Thanks,
      >
      > shark[/color]

      Just out of curiosity, why would you want to do that? Are you trying to
      save on memory to store a lot of these things? If so, I suspect you'd
      do even better (a few bytes per object) to store tuples of just the
      values, i.e. ("Hoboken", "Alaska"), and unpack them as you need them.

      But, to answer your question, I don't know of any standard way to do
      what you want. It's easy enough to write (a production version would
      probably want to catch KeyError's inside the for loop):

      def getDictionarySl ice (row, cols):
      slice = {}
      for key in cols:
      slice[key] = row[key]
      return slice

      This won't work, but it would be kind of cool if it did:

      def getOmnicientDic tionarySlice (row, cols):
      for key not in cols:
      del row[key]

      Hmmm. Maybe there's an April Fools PEP in there somewhere :-)
      Actually, you could do:

      def deleteUnwantedK eysInPlace (row, cols):
      for key in row.keys():
      if key not in cols:
      del row[key]

      Comment

      • Stefan Behnel

        #4
        Re: Syntax for extracting multiple items from a dictionary



        shark schrieb:[color=blue]
        > row = {"fname" : "Frank", "lname" : "Jones", "city" : "Hoboken", "state" :
        > "Alaska"}
        > cols = ("city", "state")
        >
        > Is there a best-practices way to ask for an object containing only the keys
        > named in cols out of row? In other words, to get this:
        > {"city" : "Hoboken", "state" : "Alaska"}[/color]

        Untested:

        dict( (key,value) for (key,value) in row.iteritems() if key in cols )

        Works in Py2.4

        Stefan

        Comment

        • anton muhin

          #5
          Re: Syntax for extracting multiple items from a dictionary

          Stefan Behnel wrote:[color=blue]
          >
          >
          > shark schrieb:
          >[color=green]
          >> row = {"fname" : "Frank", "lname" : "Jones", "city" : "Hoboken",
          >> "state" :
          >> "Alaska"}
          >> cols = ("city", "state")
          >>
          >> Is there a best-practices way to ask for an object containing only the
          >> keys
          >> named in cols out of row? In other words, to get this:
          >> {"city" : "Hoboken", "state" : "Alaska"}[/color]
          >
          >
          > Untested:
          >
          > dict( (key,value) for (key,value) in row.iteritems() if key in cols )
          >
          > Works in Py2.4
          >
          > Stefan[/color]

          Or dict((key, row[key]) for key in cols).

          regards,
          anton.

          Comment

          • Bengt Richter

            #6
            Re: Syntax for extracting multiple items from a dictionary

            On Tue, 30 Nov 2004 15:20:19 +0100, Stefan Behnel <behnel_ml@gkec .informatik.tu-darmstadt.de> wrote:
            [color=blue]
            >
            >
            >shark schrieb:[color=green]
            >> row = {"fname" : "Frank", "lname" : "Jones", "city" : "Hoboken", "state" :
            >> "Alaska"}
            >> cols = ("city", "state")
            >>
            >> Is there a best-practices way to ask for an object containing only the keys
            >> named in cols out of row? In other words, to get this:
            >> {"city" : "Hoboken", "state" : "Alaska"}[/color]
            >
            >Untested:
            >
            >dict( (key,value) for (key,value) in row.iteritems() if key in cols )[/color]

            If there's an overall why for doing it at all, why not just iterate through
            keys of interest? I.e., (untested)

            dict( (key, row[key]) for key in cols )
            [color=blue]
            >
            >Works in Py2.4
            >
            >Stefan[/color]

            Regards,
            Bengt Richter

            Comment

            • Bengt Richter

              #7
              Re: Syntax for extracting multiple items from a dictionary

              On Tue, 30 Nov 2004 21:54:46 GMT, bokr@oz.net (Bengt Richter) wrote:
              [...][color=blue]
              >
              >If there's an overall why for doing it at all, why not just iterate through
              >keys of interest? I.e., (untested)
              >
              > dict( (key, row[key]) for key in cols )
              >[/color]
              Sorry Anton, I didn't see your post. Newsfeed delays seem
              to make this kind of duplication fairly likely ;-/

              Regards,
              Bengt Richter

              Comment

              • Dave Merrill

                #8
                Re: Syntax for extracting multiple items from a dictionary

                "anton muhin" wrote:[color=blue]
                > Stefan Behnel wrote:[color=green]
                > >
                > >
                > > shark schrieb:
                > >[color=darkred]
                > >> row = {"fname" : "Frank", "lname" : "Jones", "city" : "Hoboken",
                > >> "state" :
                > >> "Alaska"}
                > >> cols = ("city", "state")
                > >>
                > >> Is there a best-practices way to ask for an object containing only the
                > >> keys
                > >> named in cols out of row? In other words, to get this:
                > >> {"city" : "Hoboken", "state" : "Alaska"}[/color]
                > >
                > >
                > > Untested:
                > >
                > > dict( (key,value) for (key,value) in row.iteritems() if key in cols )
                > >
                > > Works in Py2.4
                > >
                > > Stefan[/color]
                >
                > Or dict((key, row[key]) for key in cols).
                >
                > regards,
                > anton.[/color]

                I'm on Py 2.3.3, and neither of these appear to work. Can someone confirm? I
                can't see anything in the 2.4 release notes that point to where this would
                have changed.

                Thanks,

                shark


                Comment

                • Simon Brunning

                  #9
                  Re: Syntax for extracting multiple items from a dictionary

                  On Wed, 1 Dec 2004 10:23:28 -0500, Dave Merrill <dmerrillq@usaq .netq> wrote:[color=blue]
                  > "anton muhin" wrote:[color=green]
                  > > Or dict((key, row[key]) for key in cols).[/color]
                  >
                  > I'm on Py 2.3.3, and neither of these appear to work. Can someone confirm? I
                  > can't see anything in the 2.4 release notes that point to where this would
                  > have changed.[/color]

                  They use generator expressions, which were introduced by Python 2.4.
                  See <http://www.python.org/dev/doc/devel/whatsnew/node4.html>.

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

                  Comment

                  • Jean Brouwers

                    #10
                    Re: Syntax for extracting multiple items from a dictionary


                    The correct syntax is:

                    dict([(key, row[key]) for key in cols])

                    i.e. the list must be enclosed in [...].

                    /Jean Brouwers



                    In article <7OednTjJLOltfD DcRVn-og@rcn.net>, Dave Merrill
                    <dmerrillq@usaq .netq> wrote:
                    [color=blue]
                    > "anton muhin" wrote:[color=green]
                    > > Stefan Behnel wrote:[color=darkred]
                    > > >
                    > > >
                    > > > shark schrieb:
                    > > >
                    > > >> row = {"fname" : "Frank", "lname" : "Jones", "city" : "Hoboken",
                    > > >> "state" :
                    > > >> "Alaska"}
                    > > >> cols = ("city", "state")
                    > > >>
                    > > >> Is there a best-practices way to ask for an object containing only the
                    > > >> keys
                    > > >> named in cols out of row? In other words, to get this:
                    > > >> {"city" : "Hoboken", "state" : "Alaska"}
                    > > >
                    > > >
                    > > > Untested:
                    > > >
                    > > > dict( (key,value) for (key,value) in row.iteritems() if key in cols )
                    > > >
                    > > > Works in Py2.4
                    > > >
                    > > > Stefan[/color]
                    > >
                    > > Or dict((key, row[key]) for key in cols).
                    > >
                    > > regards,
                    > > anton.[/color]
                    >
                    > I'm on Py 2.3.3, and neither of these appear to work. Can someone confirm? I
                    > can't see anything in the 2.4 release notes that point to where this would
                    > have changed.
                    >
                    > Thanks,
                    >
                    > shark
                    >
                    >[/color]

                    Comment

                    • Peter Hansen

                      #11
                      Re: Syntax for extracting multiple items from a dictionary

                      Dave Merrill wrote:[color=blue]
                      > "anton muhin" wrote:[color=green]
                      >>Or dict((key, row[key]) for key in cols).[/color]
                      >
                      > I'm on Py 2.3.3, and neither of these appear to work.[/color]

                      You're probably getting the error shown. Try the change in
                      the line following it instead.

                      Python 2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit (Intel)][color=blue][color=green][color=darkred]
                      >>> row = {'fname': 'Frank', 'lname': 'Jones', 'city': 'Hoboken',[/color][/color][/color]
                      'state': 'Alaska'}[color=blue][color=green][color=darkred]
                      >>> cols = ['city', 'state']
                      >>> dict((key, row[key]) for key in cols)[/color][/color][/color]
                      File "<stdin>", line 1
                      dict((key, row[key]) for key in cols)
                      ^
                      SyntaxError: invalid syntax[color=blue][color=green][color=darkred]
                      >>> dict([(key, row[key]) for key in cols])[/color][/color][/color]
                      {'city': 'Hoboken', 'state': 'Alaska'}

                      [color=blue]
                      > I can't see anything in the 2.4 release notes that point to where this would
                      > have changed.[/color]

                      See http://www.python.org/2.4/highlights.html and search for
                      "generator expressions".

                      -Peter

                      Comment

                      Working...