[Tutor] sorting by values in dict

Daniel Ehrenberg littledanehren at yahoo.com
Thu Nov 13 17:32:39 EST 2003


--- Paul Tremblay wrote:
> Is there a way to sort a dictionary by values?
> 
Dictionaries are unordered, so technically no. But
there are ways to sort lists derived from
dictionaries.

> My problem involves a simple script that sorts files
> by size.
> 
> I make dictionary that looks like this:
> 
> {'file1': 10000,
> 'file2'	: 10000,
> file3'	: 5000,
> }
> 
> I simply can't switch values and keys and sort by
> keys, because files
> might have the same size. For example, if I simply
> switched values and
> keys in the above dictionary, I would get:
> 
> {10000 : 'file1',
> 5000   : 'file3',
> }
> 
> Obviously, I can sort the values like this:
> 
> values = the_dict.values()
> values.sort()
> 
> But I need to know which value is associated with
> each key.
> 
> There is probably a very easy answer to this. My
> python book doesn't
> mention it.
> 
> thanks
> 
> Paul

To get a list of tuples of keys and values in
dictionary d, simply use d.items(). This is
automatically sorted using the cmp() function, as all
sorts are unless a different function is explicitly
given. Here's an example:

>>> d = {"hello":0, "world":1}
>>> x = d.items()
>>> print x #This is in a non-sensical, but
consistent, order. Sorted low to high, as Python sees
it internally.
[('world', 1), ('hello', 0)]
>>> def cmp_by_value(item1, item2):
...     return cmp(item1[1], item2[1])
...
>>> x.sort()
>>> print x #Now it should be sorted by the second
element in the tuples, increacing
[('hello', 0), ('world', 1)]
>>> x.reverse() #make it high to low instead
>>> print x
[('world', 1), ('hello', 0)]

Although it looks like it was sorted correctly the
first time, it shouldn't be that way most of the time.
Now here's a simple loop to print out the names of the
files and how big they are suitable for actual
reading:

>>> print "The files in high to low order:"
The files in high to low order:
>>> for name, size in x:
...     print "%s is %i bytes" %(name, size)
...
world is 1 bytes
hello is 0 bytes

but it would have nicer output if placed in an
external script file.

Daniel Ehrenberg

__________________________________
Do you Yahoo!?
Protect your identity with Yahoo! Mail AddressGuard
http://antispam.yahoo.com/whatsnewfree



More information about the Tutor mailing list