Rajasekar
Rajasekar

Reputation: 18948

How to order a Dictionary based on the value?

I have a Dictionary like

tel = {'jack': 18, 'sape': 4139, 'sar': 2139, 'mape': 319, 'sipe': 29}

I want to order it based on the value in descending order like

tel = {'sape': 4139, 'sar': 2139, 'mape': 319, 'sipe': 29 'jack': 18}

I searched the web a lot and found unrelated results. Is there any built-in function there or else any other way?

Upvotes: 2

Views: 238

Answers (3)

ʇsәɹoɈ
ʇsәɹoɈ

Reputation: 23479

In python 2.7 or 3.1, you can use OrderedDict:

from collections import OrderedDict
from operator import itemgetter
tel = {'jack': 18, 'sape': 4139, 'sar': 2139, 'mape': 319, 'sipe': 29}
newtel = OrderedDict(sorted(tel.items(), key=itemgetter(1), reverse=True))

More examples can be found in the What's New doc.

EDIT: Now using itemgetter instead of lambda, to please those who care. Apologies to those who found it more clear the old way.

Upvotes: 3

ceth
ceth

Reputation: 45295

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

and that can be usefull.

Upvotes: 1

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798804

There is no way to order a dict. Either use an ordered dictionary, or some other ordered sequence.

sorted(tel.iteritems(), key=operator.itemgetter(1), reverse=True)

Upvotes: 3

Related Questions