Dict Methods
dict.get()
Reads an existing value or supplies a fallback for an absent key without inserting anything. A present key associated with None, False or zero still returns its stored value. When None is a valid stored value, use membership or a unique sentinel to distinguish absence. Unhashable keys and exceptions from custom hashing or equality can still cause failure. Unlike subscription on a dict subclass, the built-in get method does not invoke __missing__.
Formal Syntax & Structure
python syntaxpython
mapping.get(key, default=None, /)Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| key | Hashable | Key to locate using hashing and equality. |
| default | object | Fallback object, returned unchanged if the key is absent. |
Return Value
object
Stored value if present; otherwise the supplied fallback.
Working Example
Example Snippetpython
prices = {"pen": 0, "book": 7}print(prices.get("pen", 5))print(prices.get("bag", 5))print(prices.get("bag"))print("bag" in prices)