简介
Python 字典(Dictionary) fromkeys() 函数用于创建一个新字典,以序列seq中元素做字典的键,value为字典所有键对应的初始值。
语法
fromkeys()方法语法:
dict.fromkeys(seq[, value])
参数
- seq – 字典键值列表
- value – 可选参数, 设置键序列(seq)的值
返回值
该方法返回列表。
实例一:展示了 fromkeys()函数的使用方法:
#!/usr/bin/python
seq = ('name', 'age', 'sex')
dict = dict.fromkeys(seq)
#不赋值
print "New Dictionary : %s" % str(dict)
#赋值10
dict = dict.fromkeys(seq, 10)
print "New Dictionary : %s" % str(dict)
#输出结果:
New Dictionary : {'age': None, 'name': None, 'sex': None}
New Dictionary : {'age': 10, 'name': 10, 'sex': 10}
实例二:请统计字符串in_str里面每个元音字母各出现了多少次
# string of vowels
# 遇到问题没人解答?小编创建了一个Python学习交流QQ群:778463939
# 寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
vowels = 'aeiou'
counter = {}.fromkeys(vowels,0)
# change this value for a different result
in_str = 'Hello, have you tried our turorial section yet?'
# make it suitable for caseless comparisions
in_str = in_str.casefold()
# make a dictionary with each vowel a key and value 0
# count the vowels
for char in in_str:
if char in counter:
counter[char] += 1
print(counter)#输出结果
{'a': 2, 'e': 5, 'i': 3, 'o': 5, 'u': 3}