Sort a Dictionary

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

    Sort a Dictionary

    This is fairly simple in PHP, how do I do it in Python?


  • Andrew Dalke

    #2
    Re: Sort a Dictionary

    Afanasiy:[color=blue]
    > This is fairly simple in PHP, how do I do it in Python?
    >
    > http://www.php.net/manual/en/function.ksort.php[/color]

    def ksort(d, func = None):
    keys = d.keys()
    keys.sort(func)
    return keys

    for k in ksort(d):
    print k, v

    As a bonus, you don't need to tell the sort to sort numerically
    vs. lexigraphically --- Python's strong typing knows that by
    default. You can pass in an alternate compare function if you
    want.

    And no, I haven't tested it. ;)

    Andrew
    dalke@dalkescie ntific.com


    Comment

    • Andrew Dalke

      #3
      Re: Sort a Dictionary

      Afanasiy:[color=blue]
      > This is fairly simple in PHP, how do I do it in Python?
      >
      > http://www.php.net/manual/en/function.ksort.php[/color]

      def ksort(d, func = None):
      keys = d.keys()
      keys.sort(func)
      return keys

      for k in ksort(d):
      print k, v

      As a bonus, you don't need to tell the sort to sort numerically
      vs. lexigraphically --- Python's strong typing knows that by
      default. You can pass in an alternate compare function if you
      want.

      And no, I haven't tested it. ;)

      Andrew
      dalke@dalkescie ntific.com


      Comment

      • Afanasiy

        #4
        Re: Sort a Dictionary

        On Sat, 23 Aug 2003 02:34:23 GMT, "Andrew Dalke" <adalke@mindspr ing.com>
        wrote:
        [color=blue]
        >Afanasiy:[color=green]
        >> This is fairly simple in PHP, how do I do it in Python?
        >>
        >> http://www.php.net/manual/en/function.ksort.php[/color]
        >
        >def ksort(d, func = None):
        > keys = d.keys()
        > keys.sort(func)
        > return keys
        >
        >for k in ksort(d):
        > print k, v
        >
        >As a bonus, you don't need to tell the sort to sort numerically
        >vs. lexigraphically --- Python's strong typing knows that by
        >default. You can pass in an alternate compare function if you
        >want.[/color]

        Why wouldn't this be a standard function?

        Comment

        • Afanasiy

          #5
          Re: Sort a Dictionary

          On Sat, 23 Aug 2003 02:34:23 GMT, "Andrew Dalke" <adalke@mindspr ing.com>
          wrote:
          [color=blue]
          >Afanasiy:[color=green]
          >> This is fairly simple in PHP, how do I do it in Python?
          >>
          >> http://www.php.net/manual/en/function.ksort.php[/color]
          >
          >def ksort(d, func = None):
          > keys = d.keys()
          > keys.sort(func)
          > return keys
          >
          >for k in ksort(d):
          > print k, v
          >
          >As a bonus, you don't need to tell the sort to sort numerically
          >vs. lexigraphically --- Python's strong typing knows that by
          >default. You can pass in an alternate compare function if you
          >want.[/color]

          Why wouldn't this be a standard function?

          Comment

          • Afanasiy

            #6
            Re: Sort a Dictionary

            On Sat, 23 Aug 2003 02:34:23 GMT, "Andrew Dalke" <adalke@mindspr ing.com>
            wrote:
            [color=blue]
            >Afanasiy:[color=green]
            >> This is fairly simple in PHP, how do I do it in Python?
            >>
            >> http://www.php.net/manual/en/function.ksort.php[/color]
            >
            >def ksort(d, func = None):
            > keys = d.keys()
            > keys.sort(func)
            > return keys
            >
            >for k in ksort(d):
            > print k, v
            >[/color]

            How about this one?

            Sort an array in ascending order and maintain index association

            Comment

            • Afanasiy

              #7
              Re: Sort a Dictionary

              On Sat, 23 Aug 2003 02:34:23 GMT, "Andrew Dalke" <adalke@mindspr ing.com>
              wrote:
              [color=blue]
              >Afanasiy:[color=green]
              >> This is fairly simple in PHP, how do I do it in Python?
              >>
              >> http://www.php.net/manual/en/function.ksort.php[/color]
              >
              >def ksort(d, func = None):
              > keys = d.keys()
              > keys.sort(func)
              > return keys
              >
              >for k in ksort(d):
              > print k, v
              >[/color]

              How about this one?

              Sort an array in ascending order and maintain index association

              Comment

              • Andrew Dalke

                #8
                Re: Sort a Dictionary

                Afanasiy:[color=blue]
                > Why wouldn't [ksort] be a standard function?[/color]

                Because it isn't needed all that often and can be built (when needed)
                from the underlying primitives very simply. Because if there are a
                lot of similar methods then it becomes harder to remember what each
                one does.

                The normal practice is

                keys = d.keys()
                keys.sort()
                for k in keys:
                ....

                which isn't all that onerous.
                [color=blue]
                > How about this one?
                >
                > http://www.php.net/manual/en/function.asort.php[/color]

                The normal idiom for sorting by value then printing
                the key/value pairs is

                rev_items = [(v, k) for k, v in d.items()]
                rev_items.sort( )
                for v, k in rev_items:
                print k, v

                If you want that as a function return just the keys
                in value order

                def asort(d):
                rev_items = [(v, k) for k, v in d.items()]
                rev_items.sort( )
                return [k for (v, k) in rev_items]

                As you can see, there are many ways you might want
                to sort a dict. Why should all of them be present in
                the standard dict type when it's really a matter of two
                extra lines to get what you need. Seeing the code in
                this case is much easier than memorizing the 7 different
                sort functions mentioned in the PHP docs.

                Additionally, Python's keys can be more complex than
                a string or int. Eg,

                d = {}
                d[ (0,0) ] = "home"
                d[ (1,3) ] = "school"
                d[ (4,2) ] = "work"

                y_items = [(y, name) for ((x, y), name) in d.items()]
                y_items.sort()
                for y, name in y_items:
                print y, name

                sorts by y position, ignoring x position. PHP doesn't
                have a function for that, but it follows pretty naturally
                from the idiomatically Python way to do it.

                Andrew
                dalke@dalkescie ntific.com


                Comment

                • Andrew Dalke

                  #9
                  Re: Sort a Dictionary

                  Afanasiy:[color=blue]
                  > Why wouldn't [ksort] be a standard function?[/color]

                  Because it isn't needed all that often and can be built (when needed)
                  from the underlying primitives very simply. Because if there are a
                  lot of similar methods then it becomes harder to remember what each
                  one does.

                  The normal practice is

                  keys = d.keys()
                  keys.sort()
                  for k in keys:
                  ....

                  which isn't all that onerous.
                  [color=blue]
                  > How about this one?
                  >
                  > http://www.php.net/manual/en/function.asort.php[/color]

                  The normal idiom for sorting by value then printing
                  the key/value pairs is

                  rev_items = [(v, k) for k, v in d.items()]
                  rev_items.sort( )
                  for v, k in rev_items:
                  print k, v

                  If you want that as a function return just the keys
                  in value order

                  def asort(d):
                  rev_items = [(v, k) for k, v in d.items()]
                  rev_items.sort( )
                  return [k for (v, k) in rev_items]

                  As you can see, there are many ways you might want
                  to sort a dict. Why should all of them be present in
                  the standard dict type when it's really a matter of two
                  extra lines to get what you need. Seeing the code in
                  this case is much easier than memorizing the 7 different
                  sort functions mentioned in the PHP docs.

                  Additionally, Python's keys can be more complex than
                  a string or int. Eg,

                  d = {}
                  d[ (0,0) ] = "home"
                  d[ (1,3) ] = "school"
                  d[ (4,2) ] = "work"

                  y_items = [(y, name) for ((x, y), name) in d.items()]
                  y_items.sort()
                  for y, name in y_items:
                  print y, name

                  sorts by y position, ignoring x position. PHP doesn't
                  have a function for that, but it follows pretty naturally
                  from the idiomatically Python way to do it.

                  Andrew
                  dalke@dalkescie ntific.com


                  Comment

                  • mackstann

                    #10
                    Re: Sort a Dictionary

                    On Sat, Aug 23, 2003 at 02:03:09AM +0000, Afanasiy wrote:[color=blue]
                    > This is fairly simple in PHP, how do I do it in Python?[/color]

                    In PHP, associative arrays are still regular arrays too, you can access
                    them by index (IIRC), and when you loop through them, they maintain the
                    order in which you assigned their items. Python seperates associative
                    arrays (dicts/hashes) from numerically indexed arrays (lists). You
                    can't sort a dict, because a dict has no order. You could do something
                    like:

                    mydict = { ..whatever.. }

                    sortedkeys = mydict.keys()
                    sortedkeys.sort ()

                    for key in sortedkeys:
                    print key, mydict[key]

                    Then we run into the issue of why we have to do list.sort() in place,
                    and I'm sure that's been discussed here a billion times (can't say I've
                    been part of any of those discussions though).

                    --
                    m a c k s t a n n mack @ incise.org http://incise.org
                    After a few boring years, socially meaningful rock 'n' roll died out.
                    It was replaced by disco, which offers no guidance to any form of life
                    more advanced than the lichen family.
                    -- Dave Barry, "Kids Today: They Don't Know Dum Diddly Do"

                    Comment

                    Working...