List and Dictionary
List
A linear collection of values that stay in order
Dictionary
A bag of values, each with its own lable
Dictionaries
Dictionaries Literals
用dict()或{}创建空字典
Many Counters with a Dictionary
Dictionary Trace Back
Method
dict.get(key,value)如果原字典里没有这个key,则将该key加入字典并附值value
word count 例子:
Definite Loops and Dictionaries
Retrieving lists of keys and values
Two iteration variable for key and value
Counting Word Frequencty
# 打开文件
name = input('Enter the file name:')
handle = open(name)
# 将文件中的字词转入字典中
counts = dict()
for line in handle:
words = line.split()
for word in words:
counts = counts.get(word,0) + 1
# 计算最大的字词数
bigcount = None
bigword = None
for word, count in counts.items():
if bigcount = None or count > bigcount:
bigcount = count
bigword = word
print(bigword, bigcount)