1

I have already build a dictionary.Here is my dictionary:

mydict = {'to': 12, 'and': 35, 'Python': 26, 'for': 49}

I want to sort this dictionary by value (from max to min) and print result like this:

for 49
and 35
Python 26
to 12

I don't know how to do it.Any help will be appreciated! I have tried:

  (1)  for key,value in mydict.items():
        print(key,sorted(mydict.values(),reverse=True))  #int is not iterable

(2)use dict.keys() and dict.values(), but I don't know how to print correspond keys.

(3)I tried to build a list for value and build a new dictionary from value's list.But I don't know how to do it.

(4)try to convert int to string,but it can't be converted! Thank you so much!

林侑萱
  • 27
  • 1
  • 4

1 Answers1

1

You want:

sorted(mydict.items(), key=lambda x: x[1], reverse=True)

So the full code would be:

for key, value in sorted(mydict.items(), key=lambda x: x[1], reverse=True):
    print(key, value)

Python's built-in sorted() function has an optional key parameter, that you can pass a lambda function (going in depth here would break the scope of the question, but it is advisable that you google it until you have a rough idea) or any function really, that will be passed each element in turn. Since in your case every element is in the form of (key, value), we use lambda to extract the value part of each element and sort accordingly.

TomMP
  • 715
  • 1
  • 5
  • 15