数据类型划分:可变数据类型,不可变数据类型
不可变数据类型:元祖 bool int str 可哈希
可变数据类型:list,dic set 不可哈希
dict key 必须是不可变数据类型,可哈希
value:任何数据类型
dict优点:二分查找去查询
存储大量的关系型数据
特点:无序的,无索引
增
dic1={'age': 18, 'name': 'jin', 'sex': 'male', 'k': 'v'} #增 dic1['high'] = 185 #没有键值对,添加 print(dic1) dic1['age'] = 16 #存在键值对,则覆盖 print(dic1) dic1.setdefault('weight',150) #有键值对,不做任何改变,没有才增加
print(dic1)
{'high': 185, 'sex': 'male', 'k': 'v', 'age': 18, 'name': 'jin'}
{'high': 185, 'sex': 'male', 'k': 'v', 'age': 16, 'name': 'jin'}
{'sex': 'male', 'k': 'v', 'weight': 150, 'high': 185, 'age': 16, 'name': 'jin'}
删除
dic1.pop('age') #有返回值 print(dic1) print(dic1.pop('six',None)) #可设置返回值 print(dic1) dic1.popitem() #随机删除,有返回值。元祖里是删除键值 print(dic1) dic1.clear() #清空字典 print(dic1) del dic1['name'] print(dic1) {'name': 'jin', 'sex': 'male', 'k': 'v'} None {'name': 'jin', 'sex': 'male', 'k': 'v'} {'sex': 'male', 'k': 'v'} {} {'age': 18, 'sex': 'male', 'k': 'v'}
改
dic1['age']=16 print(dic1) dic = {"name":"jin","age":18,"sex":"male"} dic2 = {"name":"alex","weight":75} dic2.update(dic) # 将dic所有的键值对覆盖添加(相同的覆盖,没有的添加)到dic2中 print(dic) print(dic2) {'name': 'jin', 'age': 16, 'k': 'v', 'sex': 'male'} {'name': 'jin', 'age': 18, 'sex': 'male'} {'weight': 75, 'name': 'jin', 'age': 18, 'sex': 'male'}
查
dic1={'age': 18, 'name': 'jin', 'sex': 'male', 'k': 'v'} print(dic1.keys(),type(dic1.keys())) print(dic1.values()) print(dic1.items()) dict_keys(['age', 'sex', 'k', 'name']) <class 'dict_keys'> dict_values([18, 'male', 'v', 'jin']) dict_items([('age', 18), ('sex', 'male'), ('k', 'v'), ('name', 'jin')])
print(dic1.get('name1',‘no this key’)) #不会报错
no this key
字典循环
for i in dic1: print(i) name k age sex for i in dic1.keys(): print(i) name k age sex for i in dic1.items(): print(i) ('name', 'jin') ('k', 'v') ('age', 18) ('sex', 'male') for i in dic1.values(): print(i) jin v 18 male a = 1 b = 2 a,b=b,a print(a,b) 2 1
for k,v in dic1.items():
print(k,v)
name jin
k v
age 18
sex male
嵌套
dic = { 'name':['alex','wusir','taibai'], 'py9' :{ 'time':'1213', 'learn_money':19800, 'addr':'CBD', }, 'age':21 } dic['age']=56 print(dic['name']) dic['name'].append('ritian') print(dic) dic['name'][1] = dic['name'][1].upper() print(dic) l = [1,2,'wusi'] l[2]=l[2].upper() print(l) dic['py9'] ['femail']=6 print(dic) {'name': ['alex', 'wusir', 'taibai', 'ritian'], 'age': 56, 'py9': {'learn_money': 19800, 'time': '1213', 'addr': 'CBD'}} {'name': ['alex', 'WUSIR', 'taibai', 'ritian'], 'age': 56, 'py9': {'learn_money': 19800, 'time': '1213', 'addr': 'CBD'}} [1, 2, 'WUSI'] {'name': ['alex', 'WUSIR', 'taibai', 'ritian'], 'age': 56, 'py9': {'learn_money': 19800, 'time': '1213', 'addr': 'CBD', 'femail': 6}}
info =input('>>>') for i in info: if i.isalpha(): info = info.replace(i," ") l = info.split() print(len(l)) >>>123ab123 2