如题
1AbbenMar 24, 2020在python3.6及以上:x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0} {k: v for k, v in sorted(x.items(), key=lambda item: item[1])} {0: 0, 2: 1, 1: 2, 4: 3, 3: 4}在python3.6以下:字典是不能被排序的,只能获得一个按照value排序后的字典表示,因为字典本身就是无序的,不像list或者tuple是有序的,所以你需要一个有序的容器去存储。例如:import operator x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0} sorted_x = sorted(x.items(), key=operator.itemgetter(1))或者:import collections sorted_dict = collections.OrderedDict(sorted_x)
1AbbenMar 24, 2020如果字典的value是数字类型,那么可以借助Counterfrom collections import Counter x = {'hello': 1, 'python': 5, 'world': 3} c = Counter(x) print(c.most_common()) >> [('python', 5), ('world', 3), ('hello', 1)]
在python3.6及以上:
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0} {k: v for k, v in sorted(x.items(), key=lambda item: item[1])} {0: 0, 2: 1, 1: 2, 4: 3, 3: 4}
在python3.6以下:
字典是不能被排序的,只能获得一个按照value排序后的字典表示,因为字典本身就是无序的,不像list或者tuple是有序的,所以你需要一个有序的容器去存储。
例如:
import operator x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0} sorted_x = sorted(x.items(), key=operator.itemgetter(1))
或者:
import collections sorted_dict = collections.OrderedDict(sorted_x)
如果字典的value是数字类型,那么可以借助Counter
from collections import Counter x = {'hello': 1, 'python': 5, 'world': 3} c = Counter(x) print(c.most_common()) >> [('python', 5), ('world', 3), ('hello', 1)]
OR
sorted((value,key) for (key,value) in mydict.items())