Reputation: 51251
d = { 'a':{'k':1, 'b':'whatever'}, 'b':{'k':2, 'b':'sort by k'} }
Want to sort this dictionary by k as descending order, in python.
Little tricky, please help.
Upvotes: 19
Views: 14596
Reputation: 1926
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')))
Upvotes: 3
Reputation: 11
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
Upvotes: 0
Reputation: 66709
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:
A drop-in substitute for Py2.7's new collections.OrderedDict that works in Python 2.4-2.6.
Upvotes: 5
Reputation: 879571
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.
Upvotes: 21
Reputation: 61515
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.
Upvotes: 1