Dictionaries and default values

mnowotka picture mnowotka · Feb 20, 2012 · Viewed 200.1k times · Source

Assuming connectionDetails is a Python dictionary, what's the best, most elegant, most "pythonic" way of refactoring code like this?

if "host" in connectionDetails:
    host = connectionDetails["host"]
else:
    host = someDefaultValue

Answer

MattH picture MattH · Feb 20, 2012

Like this:

host = connectionDetails.get('host', someDefaultValue)