1 背景
Python字典的get()方法介绍
今天看到一个字典用法,自己学习一下。
2 字典常用初始化
下面这个方式,应该是最常见的吧。
dictOne = {"one":1,"two":1}
myList = ["three", "four"]
for i in Mylist:
if i in dictOne:
dictOne[i] + =1
else:
dictOne[i] =1
3 get()方法介绍
有幸看到了下面这个用法(最后一行)
import jieba # jieba中文分词库
with open('test.txt', 'r', encoding='UTF-8') as novelFile:
novel = novelFile.read()
# print(novel)
stopwords = [line.strip() for line in open('stop.txt', 'r', encoding='UTF-8').readlines()]
novelList = list(jieba.lcut(novel))
novelDict = {}
# 统计出词频字典
for word in novelList:
if word not in stopwords:
# 不统计字数为一的词
if len(word) == 1:
continue
else:
novelDict[word] = novelDict.get(word, 0) + 1
novelDict[word] = novelDict.get(word, 0) + 1
这行代码就等于我们开始定义的那个常用用法。
如果novelDict这个字典里面存在,就加1,不然就设置一个默认值0给这个key
下面在来一个例子:
dict_data ={1:'one',2:'two',3:'three',4:'four'}
print(dict_data.get(1))
print(dict_data.get(2))
print(dict_data.get(5))
print(dict_data.get(5,'notfound'))
运行结果
one
two
None
not found
4 总结:
dict.get(key, 0) + 1
这个操作好自然,舒服!!!