篇首语:本文由小编为大家整理,主要介绍了Python字典的get()方法介绍相关的知识,希望对你有一定的参考价值。
Python字典的get()方法介绍
今天看到一个字典用法,自己学习一下。
下面这个方式,应该是最常见的吧。
dictOne = "one":1,"two":1myList = ["three", "four"]for i in Mylist:if i in dictOne: dictOne[i] + =1else:dictOne[i] =1
有幸看到了下面这个用法(最后一行)
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'))
运行结果
onetwoNonenot found
dict.get(key, 0) + 1
这个操作好自然,舒服!!!
以上是关于Python字典的get()方法介绍的主要内容,如果未能解决你的问题,请参考以下文章