dict.get()
更新字典里的键值对有时会碰到键不存在的情况,对于这种情况,除了在建立字典时就加入键之外,还可以用dict.get()
函数来解决。
$ pydoc dict.get
Help on method_descriptor in dict:
dict.get = get(...)
D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.
(END)
就如文档里说明的,使用dict.get(k,d),如果k已经在字典里,则返回dict['k'],否则返回d(默认值为None)
举例说明,比如我们想算一个文档中的词频
doc = \
'''
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
'''
count = {}
for word in doc.split():
count[word] = count.get(word,0) + 1
print count
{'Beautiful': 1, 'Python,': 1, 'Explicit': 1, 'than': 4, 'complex.': 1, 'Simple': 1, 'of': 1, 'is': 4, 'Zen': 1, 'Peters': 1, 'better': 4, 'Tim': 1, 'Complex': 1, 'ugly.': 1, 'implicit.': 1, 'The': 1, 'by': 1, 'complicated.': 1}