使用sorted和OrderedDict 对字典排序

使用sorted和OrderedDict 对字典排序
https://blog.csdn.net/qq_34732088/article/details/79917192

test = {1: "a", 3: "d", 6: "g", 2: "c", 5: "e", 0: "f", 4: 'b'}

# 对字典的key值列表排序,返回列表
print(sorted(test.keys()))

# 对字典的键值对元组列表排序,按元组的第1个元素排序,也就是 key
# 返回的是一个元组列表
print(sorted(test.items(), key=lambda obj: obj[0]))

# 对字典的键值对元组列表排序,按元组的第2个元素排序,也就是 value
# 返回的是一个元组列表
print(sorted(test.items(), key=lambda obj: obj[1]))

[0, 1, 2, 3, 4, 5, 6]
[(0, 'f'), (1, 'a'), (2, 'c'), (3, 'd'), (4, 'b'), (5, 'e'), (6, 'g')]
[(1, 'a'), (4, 'b'), (2, 'c'), (3, 'd'), (5, 'e'), (0, 'f'), (6, 'g')]

from collections import OrderedDict

test = {1: "a", 3: "d", 6: "g", 2: "c", 5: "e", 0: "f", 4: 'b'}

print(OrderedDict(sorted(test.items(), key=lambda obj: obj[0])))
print(OrderedDict(sorted(test.items(), key=lambda obj: obj[1])))

OrderedDict([(0, 'f'), (1, 'a'), (2, 'c'), (3, 'd'), (4, 'b'), (5, 'e'), (6, 'g')])
OrderedDict([(1, 'a'), (4, 'b'), (2, 'c'), (3, 'd'), (5, 'e'), (0, 'f'), (6, 'g')])

dict() vs collections.OrderedDict()
https://blog.csdn.net/weixin_38145317/article/details/104971207
如果是普通的字典,即使传入的顺序不一样,但是依然是相同的字典;如果是orderedDict,传入的顺序不一样,那么得到的字典是不一样的。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值