Quantcast
Channel: Hacking Corner
Viewing all articles
Browse latest Browse all 20

Sorting dicts by value in python

$
0
0

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:

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

Eventually you end up with something like:

[python]
d = {'joe': 8, 'sue': 5, 'bob': 3}
[/python]

Then you want to show these sorted by value:

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

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

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

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


Viewing all articles
Browse latest Browse all 20

Trending Articles