python---数据类型---字典
字典学习
1 dict = { 2 'stu1101':"Peter", 3 'stu1102':"Jack", 4 'stu1103':"Alex", 5 } 6 print(dict) 7 print(dict.values()) #打印字典里的值 8 print(dict.keys()) #打印字典里的key 9 10 dict.setdefault("stu1105","LC") #如果key存在,则返回原有的值,如果key不存在,则添加key和相应的值到字典里 11 print(dict) 12 13 dict2 ={ 14 "stu1101":"GL", 15 1:2, 16 3:5, 17 } 18 dict.update(dict2) #更新字典,如果dict2中的key在dict中存在,则更新dict中key对应的值,如果没有,则添加至dict中 19 print(dict) 20 21 print(dict.items()) #将字典变成一个列表 22 23 24 c = dict.fromkeys(["LC","HL","GL"],["classmate",{"Name":"XLL"},"19"]) #前面为key,后面赋值给key,如果修改Value,则会所有改 25 print(c)
打印结果:
{'LC': ['classmate', {'Name': 'XLL'}, '19'], 'HL': ['classmate', {'Name': 'XLL'}, '19'], 'GL': ['classmate', {'Name': 'XLL'}, '19']}
26 c["LC"][1]["Name"]="Xlingling" 27 print(c)
打印结果:
{'LC': ['classmate', {'Name': 'Xlingling'}, '19'], 'HL': ['classmate', {'Name': 'Xlingling'}, '19'], 'GL': ['classmate', {'Name': 'Xlingling'}, '19']}
28 29 #字典循环 30 for i in dict: #i表示字典里的key 31 print(i,dict[i]) 32 35 #查找 36 dict1 = dict['stu1101'] #查找,但必须确认key值是存在,否则会报错 37 dict.get('stu1101') #查找,如果不存在key,则返回None 38 dict2 = 'stu1101' in dict #如果在字典内,则返回True,否则为Fasle 39 40 dict["stu1101"]="Will" #修改字典 41 dict["stu1104"]="Mark" #增加,如果key在字典中没有,则添加 42 43 #删除 44 del dict["stu1101"] #删除字典key和值 45 dict.popitem() #随机删除 46 dict.pop("stu1102") #删除指定key和值 47 ''' 48 #多层字典嵌套 49 ''' 50 dict ={ 51 "Europe":{ 52 "Denmark":["child","pipe"], 53 "Germany":["moto","Volk"], 54 "Net":["flower","girl"] 55 }, 56 "ASPA":{ 57 "China":["people","money"], 58 "Japan":["beautiful girl","Toyota-hot"] 59 }, 60 "Americam":{ 61 "North":["write","black"], 62 "East":["basketball","football"] 63 } 64 } 65 dict["Europe"]["Net"]=["wind","farmer"] #修改嵌套字典信息 66 print(dict)