Home > tips > Sorting dicts by value in python

Sorting dicts by value in python

November 27th, 2009

A couple of tips (read: notes to self:) using sorted() and lambda to sort dicts by values in python.

Often you need to count occurrences of previously-unknown keys. The most usual way is to store these in a dict like this:

d = {}
d[key] = d.get(key, 0) + 1

Eventually you end up with something like:

d = {'joe': 8, 'sue': 5, 'bob': 3}

Then you want to show these sorted by value:

dsorted = sorted(d.iteritems(), key = lambda (k, v) : (v, k))
# dsorted = [('bob', 3), ('sue', 5), ('joe', 8)]

Another example, a list with dicts, and you want to sort the items by a dict value, this time reversed:

l = [{'count': 5}, {'count': 80}, {'count': 8}]
lsorted = sorted(l, key=lambda el : el['count'], reverse=True)
# lsorted = [{'count': 80}, {'count': 8}, {'count': 5}]

Map + lambda is another nice combination to keep in mind :)

tips ,

  1. No comments yet.
  1. No trackbacks yet.