patternpythonCriticalCanonical
Why dict.get(key) instead of dict[key]?
Viewed 0 times
keywhydictinsteadget
Problem
I came across the
For what purpose is this function useful? If I wanted to find a value associated with a key in a dictionary, I can just do
See also: Return a default value if a dictionary key is not available
dict method get which, given a key in the dictionary, returns the associated value.For what purpose is this function useful? If I wanted to find a value associated with a key in a dictionary, I can just do
dict[key], and it returns the same thing:dictionary = {"Name": "Harry", "Age": 17}
dictionary["Name"] == dictionary.get("Name") # True
See also: Return a default value if a dictionary key is not available
Solution
It allows you to provide a default value if the key is missing:
returns
would raise a
If omitted,
returns
would.
dictionary.get("bogus", default_value)returns
default_value (whatever you choose it to be), whereasdictionary["bogus"]would raise a
KeyError. If omitted,
default_value is None, such thatdictionary.get("bogus") # <-- No default specified -- defaults to Nonereturns
None just like dictionary.get("bogus", None)would.
Code Snippets
dictionary.get("bogus", default_value)dictionary["bogus"]dictionary.get("bogus") # <-- No default specified -- defaults to Nonedictionary.get("bogus", None)Context
Stack Overflow Q#11041405, score: 1710
Revisions (0)
No revisions yet.