Python 字典排序

目录

Sort a dictionary by value
依据字典的值进行排序

newDict = {k: v for k, v in sorted(x.items(), key=lambda item: item[1])}
import operator


# 示例字典
d = {'a': 3, 'e': 4, 'b': 2, 'c': 5, 'd': 1}


# 按 key 排序
def dict_sort_by_key(d: dict):
    sorted_d = sorted(d.items(), key=operator.itemgetter(0))
    return dict(sorted_d)

# 按 value 排序
def dict_sort_by_val(d: dict):
    # sorted_dic = dict(sorted(d.items(), key=operator.itemgetter(1)))
	
	sorted_keys=sorted(dict1, key=dict1.get)
	for k in sorted_keys:
		sorted_dic[k]=d[k]
	
    return sorted_dic


print(dict_sort_by_key(d))
# {'a': 3, 'b': 2, 'c': 5, 'd': 1, 'e': 4}

print(dict_sort_by_val(d))
# {'d': 1, 'b': 2, 'a': 3, 'e': 4, 'c': 5}