python 字典 setdefault()和get()方法比较详解
2019-08-07 14:43
1191 查看
dict.setdefault(key, default=None)
--> 有key获取值,否则设置 key:default,并返回default,default默认值为None
dict.get(key, default=None)
--> 有key获取值,否则返回default。default默认值为None。
例子:循环迭代message字符串中每个字符,计算每个字符出现的次数
import pprint message = "It is a good day, is not it?I mean the weather is good today." count1 = {} for char in message: count1.setdefault(char, 0) count1[char] += 1 count2 = {} for char in message: count2[char] = count2.get(char, 0) + 1 pprint.pprint(count1) pprint.pprint(count2)
扩展:
defaultdict:属于collections 模块下的一个工厂函数,用于构建字典对象,接收一个函数(可调用)对象为作为参数。参数返回的类型是什么,key对应value就是什么类型。
例子:
一般写法:
data = [("p", 1), ("p", 2), ("p", 3), ("h", 1), ("h", 2), ("h", 3)] result = {} for (key, value) in data: if key not in result: result[key] = [] result[key].append(value)
setdefault:
result = {} data = [("p", 1), ("p", 2), ("p", 3), ("h", 1), ("h", 2), ("h", 3)] for (key, value) in data: result.setdefault(key, []).append(value)
defaultdict:
from collections import defaultdict result = defaultdict(list) data = [("p", 1), ("p", 2), ("p", 3), ("h", 1), ("h", 2), ("h", 3)] for (key, value) in data: result[key].append(value)
以上就是本文的全部内容,希望对大家的学习有所帮助
您可能感兴趣的文章:
相关文章推荐
- python基础入门详解(文件输入/输出 内建类型 字典操作使用方法)
- python 字典(dict)get方法应用
- Python比较配置文件的方法实例详解
- python两种遍历字典(dict)的方法比较
- Python 字典(Dictionary) get()方法
- python 字典的get()pop()方法的区别
- Python的字典get方法:从字典中获取一个值
- 【转载】Python中如何高效实现两个字典合并,三种方法比较。
- Python_元组、字典内建方法详解
- Python中字典get方法的使用
- Python3 字典 get() 方法
- python字典简单方法使用——get函数
- python 字典 get方法
- Python3 字典 setdefault() 方法
- 在Python中用get()方法获取字典键值的教程
- Python合并两个字典的常用方法与效率比较
- python 字典get方法
- python property 与get/set方法详解
- python 字典 get(),items(),iteritems()方法
- Python 字典的get()方法