-1

I have a dictionary in the following format :-

d = { 'x' : 1, 'y' : 2, 'z' : 1, 'a' : 3 }

How can I print this to shell in the following format :-

 alphabet      number
----------------------
    a            3
    y            2
    x            1
    z            1

My code to print the dictionary to shell :- (ignoring printing 'alphabet,'number' and '-----')

for key,value in sorted(d.items()):
    print("{:>10}{:>20}".format(key,value))

So I know how to use the .format method to print the dictionary, but looking at the desired output I cannot understand how to print the dictionary by largest value to the smallest value.

Any suggestions?!

senshin
  • 10,022
  • 7
  • 46
  • 59
Luke
  • 79
  • 1
  • 8
  • 1
    Look at the `key` argument of `sorted`. https://docs.python.org/3/library/functions.html#sorted and https://wiki.python.org/moin/HowTo/Sorting/ – Ry- Dec 01 '15 at 02:22
  • 1
    It would be duplicated of http://stackoverflow.com/q/613183/2218718 – cuonglm Dec 01 '15 at 02:31

2 Answers2

2

Iterate like this:

for k in sorted(d, key=d.get, reverse=True):
    print("{:>10}{:>20}".format(k, d[k]))
wim
  • 338,267
  • 99
  • 616
  • 750
1

It would be,

>>> d = { 'x' : 1, 'y' : 2, 'z' : 1, 'a' : 3 }
>>> for i,j in sorted(d.items(), key=lambda x: x[1], reverse=True):
    print("{:>10}{:>20}".format(i,j))


         a                   3
         y                   2
         x                   1
         z                   1
>>> 
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274