python dict: get vs setdefault

前端 未结 8 1080
误落风尘
误落风尘 2020-12-04 15:04

The following two expressions seem equivalent to me. Which one is preferable?

data = [(\'a\', 1), (\'b\', 1), (\'b\', 2)]

d1 = {}
d2 = {}

for key, val in d         


        
8条回答
  •  失恋的感觉
    2020-12-04 16:08

    There is no strict answer to this question. They both accomplish the same purpose. They can both be used to deal with missing values on keys. The only difference that I have found is that with setdefault(), the key that you invoke (if not previously in the dictionary) gets automatically inserted while it does not happen with get(). Here is an example: Setdefault()

    >>> myDict = {'A': 'GOD', 'B':'Is', 'C':'GOOD'} #(1)
    >>> myDict.setdefault('C')  #(2)
    'GOOD'
    >>> myDict.setdefault('C','GREAT')  #(3)
    'GOOD'
    >>> myDict.setdefault('D','AWESOME') #(4)
    'AWESOME'
    >>> myDict #(5)
    {'A': 'GOD', 'B': 'Is', 'C': 'GOOD', 'D': 'AWSOME'} 
    >>> myDict.setdefault('E')
    >>>
    

    Get()

    >>> myDict = {'a': 1, 'b': 2, 'c': 3}   #(1)
    >>> myDict.get('a',0)   #(2)
    1
    >>> myDict.get('d',0)   #(3)
    0
    >>> myDict #(4)
    {'a': 1, 'b': 2, 'c': 3}
    

    Here is my conclusion: there is no specific answer to which one is best specifically when it comes to default values imputation. The only difference is that setdefault() automatically adds any new key with a default value in the dictionary while get() does not. For more information, please go here !

提交回复
热议问题