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

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

提交回复
热议问题