一条小鱼干

导航

python有序字典和字典排序

1.python2.x有序字典

    import collections
	# 创建一个有序字典
    datas = collections.OrderedDict()

python3.x默认是有序字典

2.字典排序

e = {'a': 5, 'd': 3, 'c': 1, 'e': 2, 'b': 4}

以key进行排序:

e1 = dict(sorted(e.items(), key = lambda asd:asd[0]))
# {'a': 5, 'b': 4, 'c': 1, 'd': 3, 'e': 2}

以value进行排序:

e2 = dict(sorted(e.items(), key = lambda asd:asd[1]))
# {'c': 1, 'e': 2, 'd': 3, 'b': 4, 'a': 5}

以value进行排序-倒序:

e3 = dict(sorted(e.items(), key = lambda asd:asd[1], reverse = True))

注:python3.0为items(),python2.x为iteritems()

posted on 2021-07-05 18:50  一条小鱼干  阅读(327)  评论(0)    收藏  举报