A Byte of my 2.2-lb Brain

Just sharing stuff…

Sorting Dictionaries in Python

Sort by Values

Here’s a code snippet to sort dictionaries by their values.

import operator

my_dict = {"apple": 10, "banana":12, "papaya": 2, "avocado": 3}
sorted_my_dict = sorted(my_dict.items(), key=operator.itemgetter(1))

The output is a list:

[('papaya', 2), ('avocado', 3), ('apple', 10), ('banana', 12)]

To reverse the list

sorted_my_dict.reverse()

The output is:

[('banana', 12), ('apple', 10), ('avocado', 3), ('papaya', 2)]

Sort by Keys

To sort a dictionary by its keys, it is just the same except for the argument in the operator.itemgetter() function.

import operator

my_dict = {"apple": 10, "banana":12, "papaya": 2, "avocado": 3}
sorted_my_dict = sorted(my_dict.items(), key=operator.itemgetter(0))

The operator Package

As is stated in its documentation,

The operator module exports a set of efficient functions corresponding to the intrinsic operators of Python. For example, operator.add(x, y) is equivalent to the expression x+y. The function names are those used for special class methods; variants without leading and trailing __ are also provided for convenience.

The functions fall into categories that perform object comparisons, logical operations, mathematical operations, sequence operations, and abstract type tests.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Information

This entry was posted on April 17, 2015 by in Geek and tagged , , , , .
%d bloggers like this: