Answers for "python sort dictionary"

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
1

sort dictionary

#for dictionary d
sorted(d.items(), key=lambda x: x[1]) #for inceasing order
sorted(d.items(), key=lambda x: x[1], reverse=True) # for decreasing order
#it will return list of key value pair tuples
Posted by: Guest on May-23-2020
0

how to sort a dictionary py

orders = {
	'cappuccino': 54,
	'latte': 56,
	'espresso': 72,
	'americano': 48,
	'cortado': 41
}

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

for i in sort_orders:
	print(i[0], i[1])
Posted by: Guest on May-18-2021
2

python sort dictionary by key

In [1]: import collections

In [2]: d = {2:3, 1:89, 4:5, 3:0}

In [3]: od = collections.OrderedDict(sorted(d.items()))

In [4]: od
Out[4]: OrderedDict([(1, 89), (2, 3), (3, 0), (4, 5)])
Posted by: Guest on April-03-2020
0

how to sort a dictionary

markdict = {"Tom":67, "Tina": 54, "Akbar": 87, "Kane": 43, "Divya":73}
marklist = sorted(markdict.items(), key=lambda x:x[1])
sortdict = dict(marklist)
print(sortdict)
Posted by: Guest on May-24-2021

Python Answers by Framework

Browse Popular Code Answers by Language