[Tutor] Sorting Dictionary of Dictionary by certain Value

Bill Campbell bill at celestial.net
Wed Sep 24 03:09:45 CEST 2008


On Wed, Sep 24, 2008, John Fouhy wrote:
>2008/9/24 Joe Python <jopython at gmail.com>:
>> Hi Pythonistas,
>>
>> I have a large dictionary of dictionary (50,000+ keys) which has a structure
>> as follows:
>[snip]
>> I want to sort the dictionary by 'income'
>> Is there an efficient way to do the same.
>
>Note that you cannot sort a dictionary.  The best you can do is build
>a list containing the dictionary keys in the appropriate order and use
>the dictionary in combination with that list.

What you can do is create a class for the objects in the top
level dictionary, and create a __cmp__ method in that class using
cmp to compare the objects in the dictionary, finally sorting the
values.

class MyStuff(object):
    def __init__(self, name, income):
        self.name = name
        self.income = int(income)
    def cmp(self, other):
        return(cmp((-self.income, self.name), -other.income, other.name))

d = dict(
    key1 = MyStuff('john', 10000),
    key2 = MyStuff('bill', 20000),
)

vals = d.values()
vals.sort()
# vals should be sorted by income in descending order and name.

Bill
--
INTERNET:   bill at celestial.com  Bill Campbell; Celestial Software LLC
URL: http://www.celestial.com/  PO Box 820; 6641 E. Mercer Way
Voice:          (206) 236-1676  Mercer Island, WA 98040-0820
Fax:            (206) 232-9186

People who relieve others of their money with guns are called robbers. It
does not alter the immorality of the act when the income transfer is
carried out by government.


More information about the Tutor mailing list