字典(Dictionary) 的fromkeys()方法

简介

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
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
# your soultion here count the vowels
print(counter)
 
#输出结果
{'a': 0, 'e': 0, 'i': 0, 'o': 0, 'u': 0}

猜你喜欢

转载自www.cnblogs.com/kumata/p/9094671.html
今日推荐