|
import random
randomdict = {i : random.randint(50, 500) for i in range(1, 6)}
print(randomdict) # {1: 79, 2: 425, 3: 145, 4: 220, 5: 223}
name = ["张三", "李四", "王五", "李六"] # 保存名字列表
sign = ["白羊座", "双鱼座", "狮子座", "处女座"] #保存星座列表
dict1 = {i : j for i, j in zip(name, sign)} # 字典推导式
print(dict1) # {'张三': '白羊座', '李四': '双鱼座', '王五': '狮子座', '李六': '处女座'}
dict1 = {"a":10,"B":20,"C":True,"D":"hello world","e":"python教程"}
dict2 = {a:b for a,b in dict1.items() if a.isupper()}
print(dict2)
dict3 = {a.lower(): b for a, b in dict1.items()}
print(dict3)
dict4 = {a: b if a.isupper() else "error" for a, b in dict1.items()}
print(dict4)
def 字典操作(aa):
aa = {a: b +100 if isinstance(b,int) else "error" for a, b in aa.items()}
bb = {a:b for a,b in aa.items() if b!='error'}
return bb
print(字典操作(dict1))
这里将"字典操作"函数名随便改个英文字母就能运行了
|
|