python 字典 setdefault()和get()方法比较详解
人气:0dict.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)
您可能感兴趣的文章:
加载全部内容