Sort dict by value and return dict, not list of tuples

Possible Duplicate:
Python: Sort a dictionary by value

d = {"a":4, "b":12, "c":2}

If I use sorted() with lambda:

s = sorted(d.items(), key=lambda(k,v):(v,k))

I get a list tuples (key,value) but I want a dict again:

{"c":2, "a":4, "b":12}

And doing dict(the_list_of_tuples) you're back to square one.


Standard dict objects are not sorted and so do not guarantee or preserve any ordering. This is because since you usually use a dict by get a value for a key ordering is unimportant.

If you want to preserve ordering you can use an OrderedDict . This isn't sorted but does remember the order in which items are added to it. So you can create one using your key value pairs in sorted order:

>>> d = {"a":4, "b":12, "c":2}
>>> from collections import OrderedDict
>>> od = OrderedDict(sorted(d.items(), key=lambda(k,v):(v,k)))
>>> od
OrderedDict([('c', 2), ('a', 4), ('b', 12)])

This isn't possible. You can only get a sorted representation of a dict like you're getting.


Edit

Just did some research. Looks like Python 2.7 has something called OrderedDict, which would allow you to do this. Here's more information about it: http://docs.python.org/library/collections.html?highlight=ordereddict#ordereddict-examples-and-recipes


As many others pointed out you cannot as python doesn't allow you to do so (except with ordered dicts). What you could implement anyhow is something like that (python < 2.7)

>>> d = {"a":4, "b":12, "c":2}
>>> z = [(i,d[i]) for i in d]
>>> z.sort(key=lambda x: x[1])
>>> z
[('c', 2), ('a', 4), ('b', 12)]

And as now d is sorted you can perform a binary search over it to get what you want (or a normal iteration if you don't too much care about speed).

链接地址: http://www.djcxy.com/p/18156.html

上一篇: 按频率排序

下一篇: 按值排序字典并返回字典,而不是元组列表