Python – dictionary get key with default

Get dictionary key with default if not found using method get()

This is better approach in most cases.

d = {"k1" : "v1"}
print d.get("k2", "Default")
print d.get("k2")
Default
None
Env: Python 2.7.6

Get dictionary key using square brackets ([])

This will raise KeyError exception if key is not present.

d = {"k1" : "v1"}
print d["k2"]
Env: Python 2.7.6

Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments