字典练习2答案
练习2:统计s='hello alex alex say hello sb sb'中每个单词的个数。结果如:{'hello': 2, 'alex': 2, 'say': 1, 'sb': 2}
# 答案1:
s='hello alex alex say hello sb sb'
words = s.split()
results = {}
for i in words:
results[i] = s.count(i)
print(results)
# 答案2:
s='hello alex alex say hello sb sb'
words = s.split()
results = {}
for i in words:
results.setdefault(i, s.count(i))
print(results)
# 答案3:
s='hello alex alex say hello sb sb'
words = s.split()
results = dict.fromkeys(words, 0)
for key in words:
results[key] += 1
print(results)