Dictionaries are like bags - no order
purse = dict()
purse['money'] = 12
purse['candy'] = 3
purse['tissues'] = 75
print(purse)
# {'money': 12, 'tissues': 75, 'candy': 3}
print(purse['candy']) # 3
purse['candy'] = purse['candy'] + 2
print(purse)
# {'money': 12, 'tissues': 75, 'candy': 5}
1.The get Method for Dictionaries
if name in counts:
x = counts[name]
else :
x = 0
可以被替代为:
//如果counts中存在name的key,那么返回它的value,否则返回0
x = counts.get(name, 0)
2.计数
counts = dict()
names = ['csev', 'cwen', 'csev', 'zqian', 'cwen']
for name in names :
counts[name] = counts.get(name, 0) + 1
# if name not in counts :
# counts[name] = 1
# else :
# counts[name] = counts[name] + 1
print(counts)
# {'csev': 2, 'zqian': 1, 'cwen': 2}
3.结合list
counts = dict()
line = input('Enter a line of text:')
words = line.split() #默认以space为分隔符
print('Words:', words)
print('Counting...')
for word in words:
counts[word] = counts.get(word, 0) + 1
print('Counts', counts)
4.dictionary和for
counts = {'chuck' : 1, 'fred' : 42, 'jan' : 100}
for key in counts:
print(key, counts[key])
#for循环里同时有两个变量
#for aaa, bbb in counts.items() :
# print(aaa, bbb)
# chuck 1
# fred 42
# jan 100
5.dictionary转化为list
jjj = {'chuck' : 1, 'fred' : 42, 'jan' : 100}
print(list(jjj))
# ['jan', 'chuck', 'fred']
print(jjj.keys())
# ['jan', 'chuck', 'fred']
print(jjj.values())
# [100, 1, 42]
print(jjj.items())
# [('jan', 100), ('chuck', 1), ('fred', 42)]
6.综合前面所学知识点的一个小实践
统计txt文件中最长出现的word并说出出现的次数
name = input('Enter file:')
handle = open(name)
#统计共有几种word,以及它们出现的次数
counts = dict()
for line in handle:
words = line.split()
for word in words:
counts[word] = counts.get(word, 0) + 1
#统计最长出现的word以及它的次数
bigcount = None
bigword = None
for word, count in counts.items(): #注意.items()不要漏掉哦!
if bigcount is None or count > bigcount:
bigword = word
bigcount = count
#输出
print(bigword, bigcount)