-3
list1 = { 'aa':4, 'ab':3, 'wr':7, 'de':6 }

I need output for this :

wr:7
de:6
aa:4
ab:3

If I need only 2 lines then how to do like - we:7 de:6

I don't want use to the import/collection function. I want to try by the for loop. if you any idea please suggest.

Ram Dayal
  • 17
  • 5

2 Answers2

0
list1 = { 'aa':4, 'ab':3, 'wr':7, 'de':6 }
print({k: v for k, v in sorted(list1.items(), key=lambda item: item[1],reverse=True)})

I've used the list comprehension to sort by the values of the dictionary

Yash Makan
  • 706
  • 1
  • 5
  • 17
0

For numeric values you can sort on the negated values to get decreasing order:

list1 = { 'aa':4, 'ab':3, 'wr':7, 'de':6 }

for k,v in sorted(list1.items(),key=lambda kv:-kv[1]):
    print(f"{k}:{v}")

wr:7
de:6
aa:4
ab:3
Alain T.
  • 40,517
  • 4
  • 31
  • 51