python的字典类型是一种保存键-值对信息条目的数据类型。例如,在一篇文章中的单词及其出现的次数就构成键-值对的信息条目,“Hello” 出现7次,“hi”出现了10次,“there”出现了45次,“at”出现了23次,“this”出现了77次。
就可以用字典类型保存这样的数据,”键“就是词,”值“就是对应的词出现的次数。
下面介绍6种创建dictionary的方法。
创建空dictionary的方法有以下两种:
# 用一对空的花括号创建空字典
wordFrequency = {}
# 用dict()创建空字典
wordFrequency = dict()
print(wordFrequency)
输出结果:{}
用键-值对的文字信息创建字典
通过传递键-值对的文字信息创建字典:
wordFrequency = {
"Hello" : 7,
"hi" : 10,
"there" : 45,
"at" : 23,
"this" : 77
}
print(wordFrequency)
输出结果如下:
{'this': 77, 'there': 45, 'hi': 10, 'at': 23, 'Hello': 7}
用dict()函数传递参数来创建函数字典
wordFrequency = dict(Hello = 7,
hi = 10,
there = 45,
at = 23,
this = 77
)
print(wordFrequency)
输出结果如下:
{'there': 45, 'hi': 10, 'this': 77, 'at': 23, 'Hello': 7}
用元组列表创建字典
假定元组列表(list of tuple)的内容如下:
listofTuples = [("Hello" , 7), ("hi" , 10), ("there" , 45),("at" , 23),("this" , 77)]
创建字典的方法如下:
wordFrequency = dict(listofTuples)
print(wordFrequency)
输出结果如下:
{'this': 77, 'there': 45, 'hi': 10, 'at': 23, 'Hello': 7}
用键的列表创建字典,然后用同样的值初始化
假定一个字符串列表的内容如下:
listofStrings = ["Hello", "hi", "there", "at", "this"]
创建一个列表,其中的键是上述字符串列表中的内容,并且默认值都为0,可以用dict()的fromkeys()函数来实现。
wordFrequency = dict.fromkeys(listofStrings,0 )
字典中的每一个元素就是字符串列表中的元素,该方法将创建键-值对并带有默认值,然后把这些数据信息保存在dict中。
print(wordFrequency)
输出结果如下:
{'this': 0, 'there': 0, 'hi': 0, 'at': 0, 'Hello': 0}
用两个列表创建字典
假定有以下两个列表,一个是字符串列表,另一个是数值列表:
listofStrings = ["Hello", "hi", "there", "at", "this"]
listofInts = [7, 10, 45, 23, 77]
用字符串列表中的元素作为键,数值列表中的元素作为值,来创建字典,可以使用zip()函数来实现,这样列表中的每一条信息都构成了键-值对。
wordFrequency = dict( zip(listofStrings,listofInts ))
print(wordFrequency)
输出结果如下:
{'this': 77, 'there': 45, 'hi': 10, 'at': 23, 'Hello': 7}

发布者:股市刺客,转载请注明出处:https://www.95sca.cn/archives/76340
站内所有文章皆来自网络转载或读者投稿,请勿用于商业用途。如有侵权、不妥之处,请联系站长并出示版权证明以便删除。敬请谅解!