Python: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
# 遇到问题没人解答?小编创建了一个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}
  • 8
    点赞
  • 51
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值