python字典有多个值的排序

Python016

python字典有多个值的排序,第1张

s = {"a":"bb","b":"cc","c":"aa"}

def fun(s):

d = sorted(s.iteritems(),key=lambda t:t[1],reverse=False)

return d

d = fun(s)

print d

iteritems() 得到的[(键,值)]的列表, 通过sorted方法,指定排序的键值key是原来字典中的value属性,其中用到了匿名函数lambda, 参数为t列表,返回第二个元素t[1],也就是每个键值对中的value, 从小到大排序时 reverse=False,从大到小排序是True!

在 Python 类的内部,无论是类属性还是实例属性,都是以字典的形式进行存储的,其中属性名作为键,而值作为该键对应的值。

为了方便用户查看类中包含哪些属性,Python 类提供了 dict 属性。需要注意的一点是,该属性可以用类名或者类的实例对象来调用,用类名直接调用 dict ,会输出该由类中所有类属性组成的字典;而使用类的实例对象调用 dict ,会输出由类中所有实例属性组成的字典。

举个例子:

程序输出结果为:

{' module ': ' main ', 'a': 1, 'b': 2, ' init ': <function CLanguage. init at 0x0000022C69833E18>, ' dict ': <attribute ' dict ' of 'CLanguage' objects>, ' weakref ': <attribute ' weakref ' of 'CLanguage' objects>, ' doc ': None}

{'name': 'C语言中文网', 'add': ' http://c.biancheng.net' }

不仅如此,对于具有继承关系的父类和子类来说,父类有自己的 dict ,同样子类也有自己的 dict ,它不会包含父类的 dict 。例如:

运行结果为:

{' module ': ' main ', 'a': 1, 'b': 2, ' init ': <function CLanguage. init at 0x000001721A853E18>, ' dict ': <attribute ' dict ' of 'CLanguage' objects>, ' weakref ': <attribute ' weakref ' of 'CLanguage' objects>, ' doc ': None}

{' module ': ' main ', 'c': 1, 'd': 2, ' init ': <function CL. init at 0x000001721CD15510>, ' doc ': None}

{'name': 'C语言中文网', 'add': ' http://c.biancheng.net' }

{'na': 'Python教程', 'ad': ' http://c.biancheng.net/python' }

除此之外,借助由类实例对象调用 dict 属性获取的字典,可以使用字典的方式对其中实例属性的值进行修改,例如:

程序运行结果为:

{'name': 'C语言中文网', 'add': ' http://c.biancheng.net' }

Python教程

#加一层判断

dict1 = dict()

for i,j in zip(g[::2],g[1::2]):

   if i not in dict1.keys(): 

       dict1[i] = j