-3
orders = {
    'apple: 54,
    'banana': 56,
    'orange': 72,
    'peach': 48,
    'grape': 41
}

Given a dictionary in this format, how can I sort the dictionary in descending order by values?

Jerry Gor
  • 13
  • 3
  • 3
    Does this answer your question? [How do I sort a dictionary by value?](https://stackoverflow.com/questions/613183/how-do-i-sort-a-dictionary-by-value) – AMC Nov 18 '20 at 01:33

2 Answers2

1

You can use the sorted function to do it.

orders = {
    'apple': 54,
    'banana': 56,
    'orange': 72,
    'peach': 48,
    'grape': 41
}

d = sorted(orders.items(), key=lambda x:x[1], reverse=True)
print(dict(d))

output:

{'orange': 72, 'banana': 56, 'apple': 54, 'peach': 48, 'grape': 41}

weijiang1994
  • 311
  • 1
  • 4
  • print (type((sorted))) gives you list, not a dict – bmjeon5957 Nov 18 '20 at 01:36
  • Please don't answer questions when it is a clear duplicate. It just encourages people to not make an effort to research the question and use existing resources. We all like to help but it just encourages the wrong activity. – The Grand J Nov 18 '20 at 01:37
0
sort_orders = sorted(orders.items(), key=lambda x: x[1], reverse=True)
Ming Hsieh
  • 713
  • 2
  • 8
  • 29
mhLi
  • 64
  • 2