Python KeyError 判斷key是否存在的2個方法:in和get() Posted on 2024-10-01Updated on 2024-10-01by 康捷QooCategories:Python 判斷key是否存在的2個方法in和get() car = { 'name':'toyota' , 'color':'blue' } car['price'] 因為沒有price,所以會產生KeyError 這時候可以用 方法一:使用in來判斷 if 'price' in car.keys(): print( car['price'] ) 方法二:使用get來判斷 car.get('price' , 'key not exist') 期待您的留言 康捷Qoo
Comments