python——字典排序

2017-01-13 19:13:51来源:CSDN作者:xiaohaimian_94人点击

第七城市

字典中有key有value,想选择其一进行排序怎么弄呢??

python>>> import operator>>>b = {'a':234,'b':1,'c':2,'e':2387}>>>print sorted(b.iteritems(),key=operator.itemgetter(0))#输出是#[('a', 234), ('b', 1), ('c', 2), ('e', 2387)]>>>print sorted(b.iteritems(),key=operator.itemgetter(1))#输出是#[[('b', 1), ('c', 2), ('a', 234), ('e', 2387)]

如果带有key的类的字典,可以这样处理:

python>>>import operator>>> class Student:        def __init__(self, name, grade, age):                self.name = name                self.grade = grade                self.age = age        def __repr__(self):                return repr((self.name, self.grade, self.age))>>> student_objects = [        Student('john', 'A', 15),        Student('jane', 'B', 12),        Student('dave', 'B', 10),]>>> sorted(student_objects, key=operator.attrgetter('age'))#输出是#[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]>>> sorted(student_objects, key=operator.attrgetter('grade'))#输出是#[('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]

参考资料:http://www.cnblogs.com/CBDoctor/p/4090900.html

第七城市

最新文章

123

最新摄影

微信扫一扫

第七城市微信公众平台