Why dict.get(key) instead of dict[key]?

后端 未结 10 2483
生来不讨喜
生来不讨喜 2020-11-21 05:51

Today, I came across the dict method get which, given a key in the dictionary, returns the associated value.

For what purpose is this funct

10条回答
  •  执笔经年
    2020-11-21 06:24

    It allows you to provide a default value if the key is missing:

    dictionary.get("bogus", default_value)
    

    returns default_value (whatever you choose it to be), whereas

    dictionary["bogus"]
    

    would raise a KeyError.

    If omitted, default_value is None, such that

    dictionary.get("bogus")  # <-- No default specified -- defaults to None
    

    returns None just like

    dictionary.get("bogus", None)
    

    would.

提交回复
热议问题