dict 字典
#内置函数len(),max(),min()都是比较的键值,所以键值必须是相同类型,dict(二维元素),enumerate()
dict1 = {5:2,2:3,3:'b',True:False};print(min(dict1))
dict2 = {'ac':1,'b':2};print(min(dict2))
print(dict1.keys()) #返回字典键的可迭代对象
print(dict1.values()) #返回字典值的可迭代对象
print(dict1.items()) #以列表返回可遍历的(键, 值) 元组数组的可迭代对象
print(dict.fromkeys((1,2,3),5)) #创建一个新字典,以序列seq中元素做字典的键,val为字典所有键对应的初始值
print(dict1.get(1,0)) #返回指定键的值,如果值不在字典中返回default值
print(dict1.setdefault(1,6)) #但如果键不存在于字典中,将会添加键并将值设为default
print([key for key in dict1]) #遍历key
print(1 in dict1) #如果键在字典dict里返回true,否则返回false
print(dict1.update(dict2));print(dict1) #把字典dict2的键/值对更新到dict1里
print(dict1.pop(1)) #删除字典给定键 key 所对应的值,返回值为被删除的值。key值必须给出。 否则,返回default值。
print(dict1.popitem()) #随机返回并删除字典中的一对键和值(一般删除末尾对)。
print(dict1.clear()) #删除字典内的所有元素
对字典的排序方法:(按照value排序)
dict3 = {3:1,5:3,2:5,'a':2,'z':99}
#方法一:
l = sorted(dict3.items(), key=lambda x: x[1], reverse=True)
print(l)
#方法二:不稳定,如果第一个值相同,第二个值是不同类型就会报错
f = zip(dict3.values(),dict3.keys())
sorted(f)
#方法三:
import operator
l1 = sorted(dict3.items(), key=operator.itemgetter)
print(l1)