您的位置:首页 > 编程语言 > Python开发

[Python高效编程] - 根据字典的大小,对字典中的项排序

2017-11-18 23:20 309 查看
Python中根据字典的大小,对字典中的项排序

开发环境

Python版本: python3.6

调试工具:pycharm 2017.1.3

电脑系统:Windows 10 64位系统

生成数据

from random import randint
data = {x: randint(60, 100) for x in 'xyzabcd'}
print(data)


{'
4000
x': 64, 'y': 61, 'z': 74, 'a': 99, 'b': 98, 'c': 62, 'd': 69}


按照值排序

直接使用sorted

from random import randint
data = {x: randint(60, 100) for x in 'xyzabcd'}
print(data)
print(sorted(data))


{'x': 97, 'y': 67, 'z': 62, 'a': 92, 'b': 67, 'c': 90, 'd': 80}
['a', 'b', 'c', 'd', 'x', 'y', 'z']


发现只是对键排序了,并没有对值排序

使用zip将数据转化为元祖排序

from random import randint
# 生成数据
data = {x: randint(60, 100) for x in 'xyzabcd'}
print(data)
# 使用zip将字典打包成元祖并排序
res = sorted(zip(data.values(), data.keys()))
print(res)


{'x': 67, 'y': 94, 'z': 66, 'a': 71, 'b': 98, 'c': 63, 'd': 69}
[(63, 'c'), (66, 'z'), (67, 'x'), (69, 'd'), (71, 'a'), (94, 'y'), (98, 'b')]


传递sorted函数key参数

from random import randint
# 生成数据
data = {x: randint(60, 100) for x in 'xyzabcd'}
print(data)
# 传递sorted函数key参数
res1 = sorted(data.items(), key=lambda x: x[1])
print(res1)


{'x': 90, 'y': 98, 'z': 84, 'a': 78, 'b': 72, 'c': 96, 'd': 99}
[('b', 72), ('a', 78), ('z', 84), ('x', 90), ('c', 96), ('y', 98), ('d', 99)]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python