d = { 'a':{'k':1, 'b':'开发者_JAVA技巧whatever'}, 'b':{'k':2, 'b':'sort by k'} }
Want to sort this dictionary by k as descending order, in python.
Little tricky, please help.
dict
s are unordered. So there is no way to sort them directly, but if you are
willing to convert the dict
into a list of (key,value)-tuples, then you could do this:
In [9]: d
Out[9]: {'a': {'b': 'whatever', 'k': 1}, 'b': {'b': 'sort by k', 'k': 2}}
In [15]: sorted(d.items(),key=lambda x: x[1]['k'],reverse=True)
Out[15]: [('b', {'b': 'sort by k', 'k': 2}), ('a', {'b': 'whatever', 'k': 1})]
This excellent mini-howto explains the use of the key
parameter.
Use OrderedDict, if you use python 2.7 or later.
Ordered dictionaries are just like regular dictionaries but they remember the order that items were inserted. When iterating over an ordered dictionary, the items are returned in the order their keys were first added.
From the example
>>> # regular unsorted dictionary
>>> d = {'banana': 3, 'apple':4, 'pear': 1, 'orange': 2}
>>> # dictionary sorted by key
>>> OrderedDict(sorted(d.items(), key=lambda t: t[0]))
OrderedDict([('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)])
For trying to achieve something of the same effect for python 2.4 or lower, see:
- http://code.activestate.com/recipes/576693/
A drop-in substitute for Py2.7's new collections.OrderedDict that works in Python 2.4-2.6.
- http://pypi.python.org/pypi/ordereddict
from collections import OrderedDict
from operator import *
d = { 'a':{'k':1, 'b':'whatever'}, 'b':{'k':2, 'b':'sort by k'} }
sorted_d = OrderedDict(sorted(d.items(), key=lambda x: getitem(x[1], 'k')))
Dictionaries are not "sorted". That isn't a meaningful concept. The keys and values are not, conceptually, in any "order" at all, so you can't change what order they're in.
If you have a dictionary (data) with sub-dictionaries (d1 and d2) containing a value (v) and priority (p), if you wanted to sort the dictionary for the intention of iterating over it then then you can do this:
data = { "d1": { "v": "hello", "p": 3}, "d2": {"v": "hi again", "p": 1},}
for item in sorted(data.keys(), key=lambda x: data[x]['p']):
print item
精彩评论