#1
  1. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2000
    Location
    Southern California
    Posts
    73
    Rep Power
    15

    sorting by value


    Let's say I want to build a map, where the key is the file name and the value is the size in bytes:

    files["foo"] = 12345

    Once it is built, I want to sort by the file size, largest first. In Perl, I could do this:

    foreach my $key (sort { $files{$b} <=> $files{$a} } keys %files)

    How do I do this in python??
  2. #2
  3. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2000
    Location
    Southern California
    Posts
    73
    Rep Power
    15
    I came up with a solution, but it may not be the best way. Opinions?

    --------------
    def sort_byval(dict, reverse=0):
    if type(dict) is not type({}): return []
    keys = dict.keys()

    s = map(lambda k: (dict[k], k), keys)
    s.sort()
    if reverse: s.reverse()

    return s
    # end sort_byval

    m = { 'a': 1000, 'b': 2000, 'c': 3000 }
    v = sort_byval(m,1)

    for v1,v2 in v: print v1

    ---------------------

    prints:
    3000
    2000
    1000
  4. #3
  5. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2001
    Location
    St. George, Utah
    Posts
    63
    Rep Power
    37
    I can't think of a better way to do it really, but I'd like to propose a change to is so it returns a sorted dictionary instead of a list of (val, key) tuples.

    Code:
    def sort_byval(dict, reverse=0):
      if type(dict) is not type({}): return []
    
      keys = dict.keys()
      s = map(lambda k: (dict[k], k), keys)
      s.sort()
    
      if reverse: s.reverse()
      
      d = {}
      for item in s:
        d[item[1]] = item[0]
    
      return d
      
      m = {'a':1000, 'b':4000, 'c':2000}
      v = sort_byval(m)
    v would now contain:
    Code:
    {'a': 1000, 'c': 2000, 'b': 4000}
    Which is the dictionary passed, sorted by value.
    Lucas Marshall
  6. #4
  7. No Profile Picture
    Junior Member
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2002
    Posts
    1
    Rep Power
    0
    Sorry, ZeUs, but dictionaries are always unsorted. You cannot rebuild a dictionary in a different order and expect it to remain that way. In fact, after a call "v = sort_byval(m)" v and m will be identical copies of each other.

    Either stick with vpopper's solution or, if you really must have a dictionary, look for sorted dictionary implementations on the Vaults of Pernassus.
  8. #5
  9. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2001
    Location
    St. George, Utah
    Posts
    63
    Rep Power
    37
    Duh.... I knew that...

    See what happens if you don't pay attention?
    Lucas Marshall

IMN logo majestic logo threadwatch logo seochat tools logo