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

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

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-11-21 06:25

    Based on usage should use this get method.

    Example1

    In [14]: user_dict = {'type': False}
    
    In [15]: user_dict.get('type', '')
    
    Out[15]: False
    
    In [16]: user_dict.get('type') or ''
    
    Out[16]: ''
    

    Example2

    In [17]: user_dict = {'type': "lead"}
    
    In [18]: user_dict.get('type') or ''
    
    Out[18]: 'lead'
    
    In [19]: user_dict.get('type', '')
    
    Out[19]: 'lead'
    
    0 讨论(0)
  • 2020-11-21 06:27

    The purpose is that you can give a default value if the key is not found, which is very useful

    dictionary.get("Name",'harry')
    
    0 讨论(0)
提交回复
热议问题