dictionary: sorting the values preserving the order
Vikram
vvikram at stanford.edu
Fri Apr 1 02:35:48 EST 2005
hi,
assuming your key-value relationship is one-to-one then as a simple first
pass you can simply initialize d1={} and for i in d.keys(): d1[d[i]] = i
and pass d1 to your sortedDictValue3 function, no?
thanks,
Vikram
On 31 Mar 2005, Rakesh wrote:
> Hi,
> For a particular problem of mine, I want to sort <key, value> pairs
> by its value.
>
> Eg:
>
> Input:
>
> A, 4
> B, 5
> C, 1
> D, 2
> E, 3
>
> I would like the output to be:
>
> C
> D
> E
> A
> B
>
> i.e. I would like to get the keys in the sorted order of values.
>
> I did google around a little bit. One solution to a similar problem
> suggested is:
>
> # Courtesy:
> http://aspn.activestate.com/ASPN/Python/Cookbook/Recipe/52306
> def sortedDictValues3(adict):
> keys = adict.keys()
> keys.sort()
> return map(adict.get, keys)
>
> This gets a list sorted by the keys. How would I get a revised
> dictionary
> sorted by its values.
>
>
More information about the Python-list
mailing list