Python内置的一种极其强大的生成字典的表达式。返回结果必须是字典
使用示例说明字典生成式
需求1:假设有20个学生,学生的分数在60~100之间,筛选出成绩在90分以上的学生
import random
#定义学生信息的字典
student = {}
for i in range(0,20):
name= 'toto'+str(i)
score = random.randint(60,100)
student[name] = score
high_score = {}
#创建一个字典 通过for 循环
for k,v in student.items():
if v > 90:
high_score[k] = v
print(high_score)
import random
student = {}
for i in range(0,20):
name= 'toto'+str(i)
score = random.randint(60,100)
student[name] = score
high_score = { k:v for k,v in student.items() if v > 90} # 使用字典生成式
print(high_score)
需求2:将所有的key值都变成大写
源字典:student = dict(toto=88, lala=90,lele=85)
student = dict(toto=88, lala=90,lele=85)
student_upper = { k.upper():v for k,v in student.items()} # 使用字典生成式
print(student_upper)
转换后输出的字典:
{'TOTO': 88, 'LALA': 90, 'LELE': 85}
需求3:大小写的key值合并,统一以小写输出
源字典:old_dict = dict(a=1,b=2,c=3,A=4,B=5)
新字典:new_dcit = {‘a’: 5, ‘b’: 7, ‘c’: 3}
old_dict = dict(a=1,b=2,c=3,A=4,B=5)
new_dcit = {}
for k,v in old_dict.items():
if k.lower() in new_dcit:
new_dcit[k.lower()] += v
else:
new_dcit[k.lower()] = v
print(new_dcit)
old_dict = dict(a=1,b=2,c=3,A=4,B=5)
#使用字典生成式
new_dcit = { k.lower():old_dict.get(k.upper(),0)+old_dict.get(k.lower(),0) for k in old_dict }
print(new_dcit)