#__author:"Feng Lin" #date: 2018/8/25 #增: dict1={‘name‘:‘lin‘,‘age‘:21,‘sex‘:‘man‘} #有键就添加 dict1[‘hight‘]=185 print(dict1) #无键就覆盖 dict1[‘age‘]=24 print(dict1) #存在键,不改变,没有才添加 dict1.setdefault(‘weight‘) print(dict1) dict1.setdefault(‘weight‘,150) dict1.setdefault(‘fat‘,150) print(dict1) #删除,有返回值,默认可自己设置 print(dict1.pop(‘lalal‘,‘没有此键‘)) #删除返回键值 print(dict1.pop(‘name‘,‘没有此键‘)) #随机删除一个键值对,返回被删除键值对的元组 print(dict1.popitem()) print(dict1) #别用del删除字典键值对,如果键不存在会报错 #del dict1[‘age‘] #del dict1[‘age1‘] #清空字典 dict1.clear() print(dict1) #改 update dict2={"name":"ou","age":21} print(dict2) dict3={"hight":187,"weight":150} dict2.update(dict3) print(dict3) print(dict2) #查 print(dict2.keys(),type(dict1.keys())) print(dict2.values()) print(dict2.items()) #嵌套 dict4={ "name":"sxixi", "time":1324, "dict5":{"age":18,"sex":"female"}, "dd":"xccd" } dict4["dict5"]["name"]="lisha" print(dict4) dict4["dict5"]["sex"]="male" print(dict4) #运用 a,b=[1,2] print(a,b) a,b=(1,2) print(a,b) #返回元组的形式 for i in dict2.items(): print(i) #这样返回可以不是元组的形式 for k,v in dict2.items(): print(k,v) #注意事项 #获取字典键值时若无此键会报错,此时用get方法,get没找到会返回None,避免报错 print(dict2.get("name1"))
原文地址:https://www.cnblogs.com/lalalaxixixi/p/9534598.html
时间: 2024-11-20 12:22:38