Python - Dictionary getter with default value

Introduction

Here are a few examples:

Demo

D = {'a': 1, 'b': 2, 'c': 3} 
print( D )#   ww w. j  a  v a 2 s  .c  o m

value = D.get('x', 0)                      # Index but with a default 
print( value )
value = D['x'] if 'x' in D else 0          # if/else expression form 
print( value )

Result

Related Topic