#max() weights = {250:'apple',125:'香蕉',300:'梨'} result = max(weights) print(result)
dict1 = {'a':22,'C':15,'E':7,'U':55,'Z':77}#键字符串类型 按照字符的编码排序 result = max(dict1) print(result)
#min() weights = {250:'apple',125:'香蕉',300:'梨'} result = min(weights) print(result)
#len() weights = {250:'apple',125:'香蕉',300:'梨'} result = len(weights) print(result)
字典的遍历
基本格式
1 2 3 4 5 6 7 8
for 变量 in 字典: 循环内容 注意:该循环中变量获取的是字典的键而非值,如果要获取值 使用字典[键变量]
shu = {'诸葛亮':'孔明','刘备':'玄德','关羽':'云长','赵云':'子龙'}
for i in shu: print(i,shu[i])
仅仅遍历字典的键
1 2 3 4 5 6
for 变量 in 字典.keys(): 循环内容
shu = {'诸葛亮':'孔明','刘备':'玄德','关羽':'云长','赵云':'子龙'} for k in shu.keys(): print(k)
仅仅遍历值
1 2 3 4 5 6
for 变量 in 字典.values(): 循环内容
shu = {'诸葛亮':'孔明','刘备':'玄德','关羽':'云长','赵云':'子龙'} for v in shu.values(): print(v)
同时遍历键和值
1 2 3 4 5 6
for 变量1,变量2in 字典.items(): 循环内容
shu = {'诸葛亮':'孔明','刘备':'玄德','关羽':'云长','赵云':'子龙'} for k,v in shu.items(): print(k,v)
字典推导式:
基本推导式
1 2 3 4 5
变量 ={变量1:变量2for 变量1,变量2in 字典.items()}
fruit = {'apple':'苹果','pear':'梨','orange':'橘子','banana':'香蕉','cherry':'樱桃'} result = {k:v for k,v in fruit.items()} print(result)
带有判断条件的推导式
1 2 3 4 5
变量 ={变量1:变量2for 变量1,变量2in 字典.items() 条件表达式}
fruit = {'apple':'苹果','pear':'梨','orange':'橘子','banana':'香蕉','cherry':'樱桃'} result = {k:v for k,v in fruit.items() if k != 'pear'} print(result)
多循环的字典推导式
1 2 3 4 5 6
变量 = {变量1 + 变量a : 变量2 + 变量b for 变量1,变量2in 字典1.items() for 变量a,变量b in 字典2.items()}
fruit = {'apple':'苹果','pear':'梨','orange':'橘子','banana':'香蕉','cherry':'樱桃'} zhushi = {'mantou':'馒头','baozi':'包子','jiaozi':'饺子'} result ={fk+zk :fv+zv for fk,fv in fruit.items() for zk,zv in zhushi.items()} print(result)
多循环的字典推导式
1 2 3 4 5 6
变量 = {变量1 + 变量a : 变量2 + 变量b for 变量1,变量2in 字典1.items() for 变量a,变量b in 字典2.items() 条件表达式}
fruit = {'apple':'苹果','pear':'梨','orange':'橘子','banana':'香蕉','cherry':'樱桃'} zhushi = {'mantou':'馒头','baozi':'包子','jiaozi':'饺子'} result ={fk+zk :fv+zv for fk,fv in fruit.items() for zk,zv in zhushi.items() if zk != 'mantou' } print(result)