Python字典的get()方法介绍

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

这个操作好自然,舒服!!!

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值