|
|
|||||||||
|
|||||||||
| |||||||||
|
|
|
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
|
|
1200+ fellow developers rate and compare features of the top IDEs, like Visual Studio, Eclipse, RAD, Delphi and others, across 13 categories. Enjoy this FREE Download of the IDE User Satisfaction Study by Evans Data Corporation. Download Now!
|
|
#1
|
||||
|
||||
|
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
|
||||
|
||||
|
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 |
|
#3
|
||||
|
||||
|
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 |
|
#4
|
|||
|
|||
|
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. |
|
#5
|
||||
|
||||
|
Duh.... I knew that...
![]() See what happens if you don't pay attention? ![]() |
![]() |
| Viewing: Dev Shed Forums > Programming Languages > Python Programming > sorting by value |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|