Answers for "python dict sort by key descending"

4

sort dictinary values from 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

reverse key order dict python

>>> a = {0:'000000',1:'11111',3:'333333',4:'444444'}
>>> a.keys()
[0, 1, 3, 4]
>>> sorted(a.keys())
[0, 1, 3, 4]
>>> reversed(sorted(a.keys()))
<listreverseiterator object at 0x02B0DB70>
>>> list(reversed(sorted(a.keys())))
[4, 3, 1, 0]
Posted by: Guest on September-14-2020
0

python reverse dict key order

# Python3 using reversed() + items()  
test_dict = {'Hello' : 4, 'to' : 2, 'you' : 5}

rev_dict = dict(reversed(list(test_dict.items()))) # Reversing the dictionary

print("The original dictionary : " + str(test_dict))
print("The reversed order dictionary : " + str(rev_dict)) 

# Output:
"The original dictionary : {'Hello': 4, 'to': 2, 'you': 5}"
"The reversed order dictionary : {'you': 5, 'to': 2, 'Hello': 4}"
Posted by: Guest on June-24-2021

Code answers related to "python dict sort by key descending"

Python Answers by Framework

Browse Popular Code Answers by Language