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)


highscore = {}
for name,score in stuInfo.items():
    if score > 90:
        highscore[name] = score
print(highscore)

 #字典生成器
    import random
    stuInfo = {'westos'+ str(i):random.randint(60,100) for
      i in range(20)}
    print({name:score for name,score in stuInfo.items() if score > 90})

需求2:将所有的key值变为大写

#一般做法
d = dict(a=1,b=2)
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=2, b=1, c=2, B=9, A=10)
print({k.lower(): d.get(k.lower(), 0) + d.get(k.upper(), 0) for k in d})
# get(key,0)如果key存在则取key所对应的value值,若不存在则取0
# 例如:k=a k=A存在,取value=2+10,当k=c时,大写C不存在则取value等于0

 #一般做法    
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)

猜你喜欢

转载自blog.csdn.net/weixin_43067754/article/details/84844392