-2

I have a dictionary, i need to sort it on the descending order of the MI Value.And print the contents in dict one by one in descending order along with 'hi'

My coding:

d = dict()
for item in a:
    specificy = c[item]
    MI1= specificx/float(specificy)
    MI2= MI1*specificx
    M13= specificx*specificy
    MI = MI1* math.log(MI1/float(MI2))
    d[x + ' ' + item] = MI

print d    
for k,v in d:
    print k + v + 'hi'
adsa lila
  • 115
  • 3
  • 11
  • Duplicated of http://stackoverflow.com/questions/4183506/python-list-sort-in-descending-order –  Mar 13 '15 at 07:11

3 Answers3

1

This should do:

import operator
for k in sorted(d.items(), key=operator.itemgetter(1), reverse=True):
    print(k + d[k] + 'hi')

It works by getting the items of the dictionary, sorting them by the values, reversed, then printing that.

See also: https://stackoverflow.com/a/613218/565635

Community
  • 1
  • 1
orlp
  • 112,504
  • 36
  • 218
  • 315
0

To sort using key change index of x to 0

for k,v in sorted(d.items(), key=lambda x: x[0], reverse=False):
    print k + v + 'hi'

To sort using value change index of x to 1

for k,v in sorted(d.items(), key=lambda x: x[1], reverse=False):
    print k + v + 'hi'
sumit-sampang-rai
  • 701
  • 1
  • 7
  • 16
0

To sort a dictionary on the item value you can use

sorted(d, key=d.__getitem__)

In your case the code becomes

for k in sorted(d, key=d.__getitem__, reverse=True):
    print(k + d[k] + "hi")

Explanation

When in Python you write

d[k]

what is evaluated is

d.__getitem__(k)

so d.__getitem__ when d is a dictionary is a function that given a key returns the value associated to that key in the dictionary.

sorted instead is a predefined function that returns a sorted version of a sequence and accepts an optional parameter (named somewhat unfortunately key, but note that key has no relation to dictionaries here). This parameter can be used to determine on what the ordering comparison should be done; sorted also supports another optional parameter reversed where you can determine if ascendant or descendant sorting is required.

Finally when a dictionary is used as a sequence (for example passing it to sorted or iterating over it in a for) what you obtain are the keys of the dictionary.

This for example implies that sorted(d, key=d.__getitem__) returns the keys of the dictionary sorted according the value.

6502
  • 112,025
  • 15
  • 165
  • 265