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

后端 未结 10 2772
生来不讨喜
生来不讨喜 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

    One difference, that can be an advantage, is that if we are looking for a key that doesn't exist we will get None, not like when we use the brackets notation, in which case we will get an error thrown:

    print(dictionary.get("address")) # None
    print(dictionary["address"]) # throws KeyError: 'address'
    

    Last thing that is cool about the get method, is that it receives an additional optional argument for a default value, that is if we tried to get the score value of a student, but the student doesn't have a score key we can get a 0 instead.

    So instead of doing this (or something similar):

    score = None
    try:
        score = dictionary["score"]
    except KeyError:
        score = 0
    

    We can do this:

    score = dictionary.get("score", 0)
    # score = 0
    

提交回复
热议问题