需求一:假设有20个学生,学生分数在60~100之间,筛选出成绩在90分以上的的学生
代码编译:

方法一 for循环:

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)

字典生成式

方法二:生成式
import random
stuinfo = {}
for i in range(20):
name = ‘westos’+str(i)
score =random.randint(60,100)
stuinfo[name]=score
print(stuinfo)
print({‘westos’+str(i):random.randint(60,100) for i in range(20)})
print({name:score for name,score in stuinfo.items() if score>90})
字典生成式

需求二:将所有的key值变成大写
代码编译:

for 循环
d =dict(a=1,b=2)
new_d ={}
for i in d:
new_d[i.upper()]=d[i]
print(‘key转化为大写的字典:’,new_d)
字典生成式

方法二:生成式
d =dict(a=1,b=2)
print({k.upper():v for k,v in d.items()})
字典生成式

需求3:大小写key合并,统一以小写输出
d =dict(a=2,b=1,c=2,B=9,A=5)
代码编译:

方法一:for循环
d =dict(a=2,b=1,c=2,B=9,A=5)
d1 ={}
for k,v in d.items():
name= k.lower()
if name not in d1:
d1[name] = v
else:
d1[name]+=v
print(d1)
字典生成式
方法二:生成式
d =dict(a=2,b=1,c=2,B=9,A=5)
print({k.lower():d.get(k.lower(),0)+d.get(k.upper(),0)for k,v in d.items()})
字典生成式

相关文章: