通过以下几个题目的练习来认识并熟悉字典生成式
1. 题目一
假设有20个学生,学生的分数在60~100之间,筛选出成绩在90分以上的学生
import random
stuInfo = {}
for i in range(20):
name = 'westos' + str(i)
score = random.randint(60, 100)
stuInfo[name] = score
print(stuInfo)
#传统方法
highscore = {}
for name, score in stuInfo.items():
if score > 90:
highscore[name] = score
print(highscore)
#字典生成式
print({name: score for name, score in stuInfo.items() if score > 90})
输出结果:
{'westos0': 100, 'westos1': 62, 'westos2': 89, 'westos3': 62, 'westos4': 82, 'westos5': 61, 'westos6': 73, 'westos7': 84, 'westos8': 70, 'westos9': 67, 'westos10': 79, 'westos11': 66, 'westos12': 71, 'westos13': 72, 'westos14': 92, 'westos15': 86, 'westos16': 91, 'westos17': 85, 'westos18': 72, 'westos19': 98}
{'westos0': 100, 'westos14': 92, 'westos16': 91, 'westos19': 98}
{'westos0': 100, 'westos14': 92, 'westos16': 91, 'westos19': 98}
2. 题目二
将所有的key值都变成大写
d = dict(a=1, b=2)
print(d)
#传统方法
new_d = {}
for i in d:
new_d[i.upper()] = d[i]
print(new_d)
#字典生成式
print({k.upper(): v for k, v in d.items()})
输出结果:
{'a': 1, 'b': 2}
{'A': 1, 'B': 2}
{'A': 1, 'B': 2}
3. 题目三
大小写的key值合并,统一以小写输出
d = dict(a=1, b=2, c=3, B=8, A=11)
#传统方法
new_d = {}
for k, v in d.items():
low_k = k.lower()
if low_k not in new_d:
new_d[low_k] = v
else:
new_d[low_k] += v
print(new_d)
#字典生成式
print({k.lower(): d.get(k.upper(), 0) +
d.get(k.lower(), 0) for k in d})
输出结果:
{'a': 12, 'b': 10, 'c': 3}
{'a': 12, 'b': 10, 'c': 3}
从上面的三个题目我们可以看出,熟练运用字典生成式,可以使代码更加简洁美观高效。