typhoonpython 2019-11-05
#定义并初始化,字典本身无序,通过key来取值。 stu_info = {"stu01":"xx1","stu02":"xx2","stu03":"xx3"} tea_info = {"tea01":"xx1", "tea02":"xx2"} #取字典的内容,直接通过key来取,如果无对应key则报错 print(stu_info["stu01"]) #"xx1" #无报错的取字典的值 print(stu_info.get("stu08")) #字典有对应key则返回value,无此key则返回None #修改字典内容,直接对key进行赋值;当无此key则为添加 stu_info["stu04"] = "xx4" #删除字典某个值 stu_info.pop("stu01") #等于del stu_info["stu01"] #判断某个key是否在字典内,返回布尔类型 print("stu01" in stu_info) #输出字典所有的值 print(stu_info.values()) #判断某个value是否在字典value内 print("xx2"in stu_info.values()) #输出字典所有的key print(stu_info.keys()) #有对应key则取出其value,无key则将实参作为key : value加入到字典内 print(stu_info.setdefault("stu02","xx9")) #两个字典合并,tea_info字典更新stu_info,相同的key以tea_info为准,不相同的key取并集 stu_info.update(tea_info) #将字典转成列表,字典每个键值对是一个元组,key是元组[0],value是元组[1] tea_info.items() #初始化一个字典,key为一个列表,第二个参数整体作为value与前面所有的key进行匹配。与列表拷贝一样,其value只能是1层,否则会出现浅拷贝的问题 dict1 = dict.fromkeys([1,2,3],["1",2]) print(dict1) #字典循环,循环字典时循环的临时变量取到的是字典的key for key in stu_info: print(key, stu_info[key])