YaleCheung
YaleCheung

Reputation: 630

How can I sort the dictionary by its value?

I used to obtain the sorted list by

dicttmp = {5:2, 2:5, 4: 3}
sorteddata = sorted(dicttmp.iteritems(), key = lambda d : d[1])

in python 2.7. From the code above, I could obtain a list, every pair of key and value in dicttmp composes a tuple as a element in the list, and the list is ordered by the value of dicttmp.

But now, I install python 3.3, I learned that the method iteritems() is not supported any longer in the users' manual. How could I obtain a list or make the dicttmp sort by its value?

Could anyone help me? Thanks very much.

Upvotes: 0

Views: 142

Answers (3)

Martijn Pieters
Martijn Pieters

Reputation: 1124858

In Python 3, dict.iteritems() was removed, just use dict.items() instead:

sorteddata = sorted(dicttmp.items(), key=lambda d: d[1])

Upvotes: 2

chepner
chepner

Reputation: 532333

In Python 3, iteritems() no longer exists; the items() method itself returns an iterator, and the only way to get a list of the items is to explicitly create one with list(dicttmp.items()).

In addition, you might want to use the itemgetter function from the operator module to supply the key function. It's a little more efficient than using a lambda expression.

from operator import itemgetter
sorted_data = sorted(dicttmp.items(), key=itemgetter(1))

Upvotes: 2

Jimmy Kane
Jimmy Kane

Reputation: 16865

One proposal is to use ordered dict:

from the examples:

>>> # regular unsorted dictionary
>>> d = {'banana': 3, 'apple':4, 'pear': 1, 'orange': 2}

>>> # dictionary sorted by key
>>> OrderedDict(sorted(d.items(), key=lambda t: t[0]))
OrderedDict([('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)])

>>> # dictionary sorted by value
>>> OrderedDict(sorted(d.items(), key=lambda t: t[1]))
OrderedDict([('pear', 1), ('orange', 2), ('banana', 3), ('apple', 4)])

>>> # dictionary sorted by length of the key string
>>> OrderedDict(sorted(d.items(), key=lambda t: len(t[0])))
OrderedDict([('pear', 1), ('apple', 4), ('orange', 2), ('banana', 3)])

Upvotes: 1

Related Questions