Skip to content

How to sort a Python dictionary by value

# How to sort a Python dict by value
# (== get a representation sorted by value)

>>> xs = {'a': 4, 'b': 3, 'c': 2, 'd': 1}

>>> sorted(xs.items(), key=lambda x: x[1])
[('d', 1), ('c', 2), ('b', 3), ('a', 4)]

# Or:

>>> import operator
>>> sorted(xs.items(), key=operator.itemgetter(1))
[('d', 1), ('c', 2), ('b', 3), ('a', 4)]

1 thought on “How to sort a Python dictionary by value”

  1. Have you ever considered including a little bit more than just your articles?
    I mean, what you say is fundamental and everything.
    Nevertheless, imagine if you added some great images or videos to give your posts more, “pop”! Your content is excellent but with images and video clips, this website could certainly be one of the most beneficial in its niche.

    Terrific blog!

Leave a Reply

Your email address will not be published. Required fields are marked *