[Tutor] Sorting Dictionary of Dictionary by certain Value
John Fouhy
john at fouhy.net
Wed Sep 24 02:59:25 CEST 2008
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.
You could try this:
1. Build a dictionary mapping income to list of families.
2. Sort keys to this dictionary.
3. Iterate through this sorted list, emitting family names.
e.g.
from collections import defaultdict
familiesByIncome = defaultdict(list)
for family in DoD:
familiesByIncome[DoD[family]['income']].append(family)
incomes = familiesByIncome.keys()
incomes.sort() # sorts from lowest to highest
familiesSorted = []
for inc in incomes:
familiesSorted.extend(familiesByIncome[inc])
##
HTH!
--
John.
More information about the Tutor
mailing list