Answers for "sort a dict python"

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
14

sort list of dictionaries by key python

newlist = sorted(list_to_be_sorted, key=lambda k: k['name'])
Posted by: Guest on March-25-2020
12

how to sort a dictionary by value in python

import operator
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = sorted(x.items(), key=operator.itemgetter(1))


# Sort by key
import operator
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = sorted(x.items(), key=operator.itemgetter(0))
Posted by: Guest on November-27-2019
3

sort list of dictionaries python

unsorted_list = [{"key1":5, "key2":2}, {"key1":5, "key2":1}]
sorted_list = sorted(unsorted_list, key=lambda k: k["key2"])
Posted by: Guest on December-13-2020
2

sort the dictionary in python

d = {2: 3, 1: 89, 4: 5, 3: 0}
od = sorted(d.items())
print(od)
Posted by: Guest on July-18-2020
0

sort dict by value python 3

>>> d = {"aa": 3, "bb": 4, "cc": 2, "dd": 1}
>>> for k in sorted(d, key=d.get, reverse=True):
...     k, d[k]
...
('bb', 4)
('aa', 3)
('cc', 2)
('dd', 1)
Posted by: Guest on September-17-2020

Python Answers by Framework

Browse Popular Code Answers by Language