Answers for "Write a python script to sort (ascending and descending) a dictionary by value."

4

python sort dictionary by value descending

Python Code:
import operator
d = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
print('Original dictionary : ',d)
sorted_d = dict(sorted(d.items(), key=operator.itemgetter(1)))
print('Dictionary in ascending order by value : ',sorted_d)
sorted_d = dict(sorted(d.items(), key=operator.itemgetter(1),reverse=True))
print('Dictionary in descending order by value : ',sorted_d)

Sample Output:
Original dictionary :  {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
Dictionary in ascending order by value :  {0: 0, 2: 1, 1: 2, 4: 3, 3: 4}
Dictionary in descending order by value :  {3: 4, 4: 3, 1: 2, 2: 1, 0: 0}
Posted by: Guest on June-06-2020
0

how to sort a list of dictionary by value in descending order?

1. new_list = sorted(old_list, key=lambda k: k['key'], reverse=True)
/*use reverse=False for ascending order*/
Posted by: Guest on June-22-2020
0

python dictionary print key value ascending order

word_dict = { 'this': 11, 'at': 9, 'here': 5, 'why': 12, 'is': 2 }
# Sort Dictionary by value in descending order using lambda function
sorted_dict = dict( sorted(word_dict.items(),
                           key=lambda item: item[1],
                           reverse=True))
print('Sorted Dictionary: ')
print(sorted_dict)
Posted by: Guest on August-07-2021

Code answers related to "Write a python script to sort (ascending and descending) a dictionary by value."

Python Answers by Framework

Browse Popular Code Answers by Language