Python Dictionary Tip used get() method


let's consider a video game like Mario. There are some levels. Here we are trying to see how we can control the key Error in the dictionary with the help of key() method.

player1 = {'mario' : 'Pro' , 'Level' :1200 }
player2 = {'mario' : 'Beginner' , 'Level' :100 }
player3 = {'mario' : 'Advance' }

all_play = [player1,player2,player3]
#print(all_play)

for p in all_play:
    lev = p['Level'] #
    print(lev)

#output
Traceback (most recent call last): File "d:\b001\get.py", line 9, in <module> lev = p['Level'] ~^^^^^^^^^ KeyError: 'Level'

 Now we can use get() method and pass 0 as a second parameter for default.

player1 = {'mario' : 'Pro' , 'Level' :1200 }
player2 = {'mario' : 'Beginner' , 'Level' :100 }
player3 = {'mario' : 'Advance' }

all_play = [player1,player2,player3]


for p in all_play:
    lev = p.get('Level',0) # to applyed get method and avoid the keyError
    print(f' Your game Levels {lev}') #applyed get() method
output :
Your game Levels 1200 Your game Levels 100 Your game Levels 0

Comments