1.5 Adding an Entry to a Dictionary


Credit: Alex Martelli

1.5.1 Problem


Working with a dictionary D, you need to use the entry D[k] if it's already present, or add a new D[k] if k isn't yet a key in D.


1.5.2 Solution


This is what the setdefault method of dictionary objects is for. Say we're building a word-to-page numbers index. A key piece of code might be:

这个是字典对象的setdefault方法所做的。 假定,我们构造一个词到页(word-to-page)的数字索引。关键的代码片断是这样的:

   1 theIndex = {} 
   2 def addword(word, pagenumber): 
   3     if theIndex.has_key(word): 
   4         theIndex[word].append(pagenumber) 
   5     else: 
   6         theIndex[word] = [pagenumber] 

Good Pythonic instincts suggest substituting this "look before you leap" pattern with an "easier to get permission" pattern (see Recipe === 5.4 for a detailed discussion of these phrases): ===

良好的python本能建议用“轻松获得许可”(easier to get permission)模式来替换掉“三思而后行”(look before you leap)模式(这些过程的详细讨论请看Recipe 5.4)


   1 def addword(word, pagenumber): 
   2     try: theIndex[word].append(pagenumber) 
   3     except AttributeError: theIndex[word] = [pagenumber] 

This is just a minor simplification, but it satisfies the pattern of "use the entry if it is already present; otherwise, add a new entry." Here's how using setdefault simplifies this further:


   1 def addword(word, pagenumber): 
   2     theIndex.setdefault(word, []).append(pagenumber) 

1.5.3 Discussion


The setdefault method of a dictionary is a handy shortcut for this task that is especially useful when the new entry you want to add is mutable. Basically, dict.setdefault(k, v) is much like dict.get(k, v), except that if k is not a key in the dictionary, the setdefault method assigns dict[k]=v as a side effect, in addition to returning v. (get would just return v, without affecting dict in any way.) Therefore, setdefault is appropriate any time you have get-like needs but also want to produce this specific side effect on the dictionary.

对于这个任务, 字典的Setdefault方法是一个便利的捷径。尤其对你想增加的新入口是可变的这种情况非常有用。如果k不是字典里的键值,setdefault方法有dict[k]=v的作用,并且返回一个v(get方法只返回v,不以任何方式影响字典)。除此之外,基本上,dict.setdefault(k, v)更象dict.get(k, v)。

setdefault is particularly useful in a dictionary with values that are lists, as detailed in Recipe 1.6. The single most typical usage form for setdefault is:

当一个字典的值是list,setdefault是非常有用的,细节在Recipe 1.6。大多数典型的使用形式是:

   1 somedict.setdefault(somekey, []).append(somevalue) 

Note that setdefault is normally not very useful if the values are immutable. If you just want to count words, for example, something like the following is no use:

注意, 当值是不可变的时候,setdefault不是非常有用。如果你仅仅想计算单词,例如,象下面这些是不能使用的:

   1 theIndex.setdefault(word, 1) 

In this case, you want:


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

since you will be rebinding the dictionary entry at theIndex[word] anyway (because numbers are immutable).


1.5.4 See Also


Recipe 5.4; the Library Reference section on mapping types.

PyCkBk-1-5 (last edited 2009-12-25 07:15:44 by localhost)