Sorting a defaultdict by value in python

imsc picture imsc · Apr 17, 2012 · Viewed 35.5k times · Source

I have a data-structure which is something like this:

The population of three cities for different year are as follows.

Name  1990 2000 2010
A     10   20   30
B     20   30   10
C     30   10   20

I am using a defaultdict to store the data.

from collections import defaultdict
cityPopulation=defaultdict(list)
cityPopulation['A']=[10,20,30]
cityPopulation['B']=[20,30,10]
cityPopulation['C']=[30,10,20]

I want to sort the defaultdict based on a particular column of the list (the year). Say, sorting for 1990, should give C,B,A, while sorting for 2010 should give A,C,B.

Also, is this the best way to store the data? As I am changing the population values, I want it to be mutable.

Answer

jamylak picture jamylak · Apr 17, 2012
>>> sorted(cityPopulation.iteritems(),key=lambda (k,v): v[0],reverse=True) #1990
[('C', [30, 10, 20]), ('B', [20, 30, 10]), ('A', [10, 20, 30])]
>>> sorted(cityPopulation.iteritems(),key=lambda (k,v): v[2],reverse=True) #2010
[('A', [10, 20, 30]), ('C', [30, 10, 20]), ('B', [20, 30, 10])]

Note in python 3 you can't automagically unpack lambda arguments so you would have to change the code

sorted(cityPopulation.items(), key=lambda k_v: k_v[1][2], reverse=True) #2010