0

I have a dictionary that looks like this

`{'a':2,'b':3,'c':2}` 

I need to print the keys and values starting with the biggest value. Desired output below:

'b' 3
'a' 2
'c' 2

The order of 'a' and 'c' does not necessarily have to be alphabetical, the important thing is that the largest value is printed first and so on.

I'm writing in python 3.

I have tried to create a new dictionary using the old values as keys and vice versa, but the issue was that I had the same values several times.

Can someone help a confused student solve this question?

juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
NiLun
  • 1
  • This is the first time i post so it got really ugly... the result im looking for is 'b' 3 on the first line and then 'a' 2 on the next and 'c' 2 on the last – NiLun Mar 13 '19 at 13:18
  • 2
    Possible duplicate of [How do I sort a dictionary by value?](https://stackoverflow.com/questions/613183/how-do-i-sort-a-dictionary-by-value) – glibdud Mar 13 '19 at 13:33
  • Please *always use the generic [python]* tag for python questions – juanpa.arrivillaga Mar 13 '19 at 18:59

2 Answers2

0

By iteritems method convert the object into a list, sort it (here with help of sortSec custom function), and then print in a loop:

def sort_sec(val): 
    return val[1]  

input = {'a':2,'b':3,'c':2}
dictlist = []

for key, value in input.iteritems():
    dictlist.append([key,value])

dictlist.sort(key=sort_sec, reverse=True)

for el in dictlist:
    print(el[0] + ' ' + str(el[1]))
vahdet
  • 6,357
  • 9
  • 51
  • 106
0

Just for the record, here's a simple solution:

dd = {'a':2,'b':3,'c':2}
ll = (zip(dd.values(), dd.keys()))
ll.sort(reverse=True) # Sorted by value
[(3, 'b'), (2, 'c'), (2, 'a')] # Print as needed
entropy
  • 840
  • 6
  • 16