dict.setdefault()
dict.setdefault() is a Python method in the Dictionary Methods category. Returns the value for key if exists, else inserts key with default and returns default. The syntax is dict.setdefault(key, default=None). Parameters: key — key to look up. Returns: Value. A typical example: d = {"a": 1}
d.setdefault("a", 42) # 1 (existing)
d.setdefault("b", 42) # 42 (inserted)
# d = {"a": 1, "b": 42}. A close sibling is dict.get(), which returns the value for key if it exists, otherwise returns default. A close sibling is dict.keys(), which returns a view object of all keys in the dictionary. A close sibling is dict.values(), which returns a view object of all values in the dictionary. A close sibling is dict.items(), which returns a view object of all (key, value) pairs as tuples. More about this category: Dictionary methods for key-value operations — get, keys, items, update, and more.