Tuesday, March 30, 2010

Python Dictionary get()

Python dictionary instances have a built in get() method that will return the value of the specified key. The method also accepts a default value to return should the key not exist. Using this method to access dictionary values is handy when you want to set a default. The alternative methods are to either manually test if the key exists or to handle a KeyError exception. The three methods are outlined below.
def use_get():
dict_obj = dict(a=1, b=2)
return dict_obj.get("c", 3)

def use_has_key():
dict_obj = dict(a=1, b=2)
if dict_obj.has_key("c"):
return dict_obj["c"]
else:
return 3

def use_key_error():
dict_obj = dict(a=1, b=2)
try:
return dict_obj["c"]
except KeyError:
return 3

if __name__ == "__main__":
print "USE GET:", use_get()
print "HAS KEY:", use_has_key()
print "KEY ERROR:", use_key_error()