python dict: get vs setdefault

前端 未结 8 1084
误落风尘
误落风尘 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:02

    1. Explained with a good example here:
    http://code.activestate.com/recipes/66516-add-an-entry-to-a-dictionary-unless-the-entry-is-a/

    dict.setdefault typical usage
    somedict.setdefault(somekey,[]).append(somevalue)

    dict.get typical usage
    theIndex[word] = 1 + theIndex.get(word,0)


    2. More explanation : http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html

    dict.setdefault() is equivalent to get or set & get. Or set if necessary then get. It's especially efficient if your dictionary key is expensive to compute or long to type.

    The only problem with dict.setdefault() is that the default value is always evaluated, whether needed or not. That only matters if the default value is expensive to compute. In that case, use defaultdict.


    3. Finally the official docs with difference highlighted http://docs.python.org/2/library/stdtypes.html

    get(key[, default])
    Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError.

    setdefault(key[, default])
    If key is in the dictionary, return its value. If not, insert key with a value of default and return default. default defaults to None.

提交回复
热议问题