user469652
user469652

Reputation: 51251

Python: sort this dictionary (dict in dict)

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

Answers (5)

cwhisperer
cwhisperer

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

Hoboken515
Hoboken515

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

pyfunc
pyfunc

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

unutbu
unutbu

Reputation: 879571

dicts 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

Karl Knechtel
Karl Knechtel

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

Related Questions