Answers for "how to sort a dictionary by its values"

35

how can I sort a dictionary in python according to its values?

s = {1: 1, 7: 2, 4: 2, 3: 1, 8: 1}
k = dict(sorted(s.items(),key=lambda x:x[0],reverse = True))
print(k)
Posted by: Guest on November-23-2020
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
1

sorting values in dictionary in python

#instead of using python inbuilt function we can it compute directly.
#here iam sorting the values in descending order..
d = {1: 1, 7: 2, 4: 2, 3: 1, 8: 1}
s=[]
for i in d.items():
  s.append(i)
for i in range(0,len(s)):
  for j in range(i+1,len(s)):
    if s[i][1]<s[j][1]:
      s[i],s[j]=s[j],s[i]
print(dict(s))
Posted by: Guest on February-14-2021

Code answers related to "how to sort a dictionary by its values"

Python Answers by Framework

Browse Popular Code Answers by Language