Python之字典生成式

需求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)
===============写成字典生成式================
stulnfo={'2050%.2d'%(i):random.randint(60,100) for i in range(20) }

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})
需求2:将所有的key值都变成大写
d = dict(a=1, b=2)
print(d)
new_d = {}
for i in d:
    new_d[i.upper()] = d[i]
print('key转换为大写的字典:',new_d)
print({k.upper(): v for k, v in d.items()})
需求3:大小写的key值合并,统一以小写输出
d = dict(a=1, b=2, c=3, B=9, A=10)
di={}
for i,v in d.items():
    if i.lower() in di:
        di[i.lower()]+=v
    else:
        di[i.lower()]=v
print(di)
===============写成字典生成式=============
print({ i.lower():d.get(i.upper(),0)+d.get(i.lower(),0) for i in d })
    原文作者:若无其事的苹果
    原文地址: https://blog.csdn.net/qq_36016375/article/details/90708427
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞