當前位置:成語大全網 - 新華字典 - python字典值的飲用方法get和字典有什麽區別

python字典值的飲用方法get和字典有什麽區別

功能很類似,但是get更適合某些場景,例如:

>>>?sample={"age":18,"height":"165cm",}?#定義壹個dict

>>>?sample['age']

18

>>>?sample['weight']

Traceback?(most?recent?call?last):

File?"<stdin>",?line?1,?in?<module>

KeyError:?'weight'

上面如果定義的sample這個dict,沒有這個weight key 則會報錯。但是,用get的方式便不會:

>>>?sample.get('weight','60kg')

'60kg'

>>>?sample.get('height','180cm')

'165cm'

所以,總結為:

sample.get('test1','test2')?#若存在sample['test1']則返回sample['test1']的值。若不存在則返回值'test2'