Sorting and list comprehension

Bryan belred1 at yahoo.com
Sun Oct 10 12:09:06 EDT 2004


Tran Tuan Anh wrote:
> Hi all,
> 
> I would like to do the followings, but I am quite new to Python hence
> have not figured it out how...
> 
> salary = dictionary
> salary["Bob"] = 11
> salary["Marry"] = 4
> salary["me"]= 45
> 
> How can I have a sort_value() function acts like this:
> result = sortvalue(salary)
> result = ["Marry","Bob","me"]
> 
> In sort, I would like to sort the key according to the values.
> 


i would do it this way which follows the DSU pattern.

 >>> salary = {}
 >>> salary['Bob'] = 11
 >>> salary['Marry'] = 4
 >>> salary['me'] = 45
 >>> tmp = [(v, k) for k, v in salary.items()]
 >>> tmp.sort()
 >>> print [k for v, k in tmp]
['Marry', 'Bob', 'me']
 >>>

bryan



More information about the Python-list mailing list