1. 1.5 Adding an Entry to a Dictionary

增加一个入口到字典里

Credit: Alex Martelli

1.1. 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.

用一个字典D工作,如果D[k]存在,使用它。如果不存在增加一个新的D[k]

1.2. 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:

这仅仅是一个次要的简化。但是它满足了“如果入口存在使用它,否则,增加新的入口”的模式。这里是怎么样使用setdefault来更进一步简化

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

1.3. 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).

因为你无论如何将重新绑定字典入口在theIndex[word]上。(因为数字是不可变的)

1.4. 1.5.4 See Also

参考

Recipe 5.4; the Library Reference section on mapping types.