python 字典的排序

在实际使用的时候,经常会碰到对python字典的排序,首先要声明的是python字典是通过哈希映射来存储,不存在顺序关系,也就谈不上排序,我们这里所说的排序实际上是 对键值对的排序,排序后返回的结果是个列表。
对字典排序有两种方法。
第一种:

import operator
dic = {‘d’:2,’b’:4,’c’:1}
b = sorted(dic.items(),key=operator.itemgetter(1))
print(b)

第二种:用 lambda方法

import operator
dic = {‘d’:2,’b’:4,’c’:1}
b = sorted(dic.items(),key=lambda x:x[1])
print(b)

你可能感兴趣的:(工具类)