Python-dictionary(课堂笔记整理)

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)
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值