1. 取键:keys()方法 #spyder bb={'人才/可怕':23,'伏地魔&波特':'army','哈哈哈,人才,回合':'hhh'} for ii in bb.keys(): print(ii) #输出: #人才/可怕 #伏地魔&波特 #哈哈哈,人才,回合 2. 取值:values()方法 for jj in bb.values(): print(jj) #输出 # #army #hhh 3. 取键值对:items()方法 for kk,vv in bb.items(): pr
1.利用key排序 d = {'d1':2, 'd2':4, 'd4':1,'d3':3,} for k in sorted(d): print(k,d[k]) d1 2d2 4d3 3d4 1 2.利用value排序:__getitem__ d = {'d1':2, 'd2':4, 'd4':1,'d3':3,} for k in sorted(d,key=d.__getitem__): print(k,d[k]) d4 1d1 2d3 3d2 4 反序:reverse=True d = {'
L = ['you','me','you','me','you','me','you'] D = {} for i in L: D[i] += 1 print(D) 执行以下代码会发生错误 Traceback (most recent call last): File line 4, in <module> D[i] += 1 KeyError: 'you' Process finished with exit code 1 为什么呢?因为我们在定义字典的时候没设置默认值,电脑找不到相应对象,