Feed on

let’s say you’ve got a dictionary keyed by strings and whose values are numbers.  if you’d like to sort those keys by those values, here’s a quick way to do so:

sorted_keys = sorted(my_dict.keys(), key=lambda x:my_dict[x])

[thanks Paul!]

Bookmark and Share

if that was helpful ...

check out the other tips and tricks i've compiled on these pages. you might learn something else interesting!

4 Responses to “sort a python dictionary”

  1. on 20 Apr 2008 at 10:04 am DoomHammer

    What Python version do you use? I got “AttributeError: ‘dict’ object has no attribute ‘sort’” with mine 2.5.2

  2. on 21 Apr 2008 at 8:24 am Lawrence David

    Hi DH,

    I’m using Python 2.5.1. And you’re right, dict’s don’t have built-in sort methods. That’s the reason for the code inside of the sort’s parentheses: I’m defining the sort method and calling it, all in one line. Try typing in the whole stretch of code and then seeing if it works.

    Good luck!

  3. on 29 Jun 2008 at 2:48 am Lie

    That doesn’t work (yes I copied the full stretch), you can’t override the attributes of built-ins (without inheritance) and dict isn’t a reliable container for sorted object in the first place, dict doesn’t even guarantee that its items would be in the order of how it’s defined.

    Something that would work would be like this:

    class myDict(dict):
    def __init__(self, init):
    def sort(self):
    # blah

    or, you may convert it into a list first (which the way you mentioned worked):
    l = list(d.iteritems())
    l.sort(cmp=lambda a,b: cmp(a[1],b[1]))

  4. on 28 Jul 2008 at 4:58 am Paul

    First off, dicts have no function sort. So you’d probably wish to either sort the items() or just the keys().

    Anyways, from (I believe) version 2.4, instead of supplying a custom cmp function, you could also supply a key function. This is calculated for the complete list only once and is thus much faster. So something like this:

    sorted_keys = sorted(my_dict.keys(), key=lambda x:my_dict[x])

    Equally you could sort the items:

    sorted_items = sorted(my_dict.items(), key=lambda x:x[1])

    Eventually this can be sped up even more by using the operator module:

    import operator
    sorted_items = sorted(my_dict.items(), key=operator.itemgetter(1))

Did I get this wrong? Let me know!

Trackback URI | Comments RSS