Python字典(dict)的setdefault()方法

如果需要统计一个字符串中每一个字符出现的次数,我会写出如下的代码:

Strings = "Welcome to my blog: blog.biochen.com!"
count = {}
for character in Strings:
	if character in count:
		count[character] = count[character] + 1
	else:
		count[character] = 0
		count[character] = count[character] + 1
print(count)

需要初始化字典中的元素的场景还是很常见的,似乎用if..else…看起来比较傻。不过Python内置了字典(dict)的setdefault()方法,上述代码可以写成这样子:

Strings = "Welcome to my blog: blog.biochen.com!"
count = {}
for character in Strings:
	count.setdefault(character, 0)
	count[character] = count[character] + 1
print(count)

dict.setdefault(key, default=None)的作用是,如果健不在字典中,将会添加健,并将值设置为默认值。
不过用if…else…比用setdefault()速度要快!!!