1.0 字典操作
dic1 = {‘name‘:‘alex‘} dic1[‘age‘] = 18 print(dic1) #>>>{‘age‘: 18, ‘name‘: ‘alex‘}
1.1 字典修改键
dic1 = {‘name‘:‘alex‘} dic1[‘name‘] = ‘wang‘ print(dic1) #>>>{‘name‘: ‘wang‘}
1.2 setdefault用法,添加键值(如果之前已经有相同键了,那么就不做修改),有返回值
dic1 = {‘name‘:‘alex‘,‘age‘:18} dic1.setdefault(‘age‘,34) print(dic1) #>>>{‘age‘: 18, ‘name‘: ‘alex‘}
dic1 = {‘name‘:‘alex‘} dic1.setdefault(‘age‘,34) print(dic1) #>>>{‘name‘: ‘alex‘, ‘age‘: 34}
1.3 setdefault返回值测试
dic1 = {‘name‘:‘alex‘} dic1[‘age‘] = 18 print(dic1) #>>>{‘name‘: ‘alex‘, ‘age‘: 18} #键存在的话,不改动,返回字典中相应的键对应的值 ret = dic1.setdefault(‘age‘,34) print(ret) #>>>18 #键不存在,在字典中增加新的键值对,并返回相应的值 ret2 = dic1.setdefault(‘hobby‘,‘girl‘) print(ret2) #>>>girl
1.4 查找
#查 通过键去查找 dic3 = {‘age‘:18,‘name‘:‘alex‘,‘hobby‘:‘girl‘} print(dic3[‘name‘]) #>>>alex print(dic3.keys()) #>>>dict_keys([‘name‘, ‘age‘, ‘hobby‘])
#查 通过键去查找 dic3 = {‘age‘:18,‘name‘:‘alex‘,‘hobby‘:‘girl‘} print(dic3[‘name‘]) #>>>alex print(dic3.keys()) #>>>dict_keys([‘name‘, ‘age‘, ‘hobby‘]) print(type(dic3.keys())) #查看类型,是个dict_keys的类 #>>><class ‘dict_keys‘> print(list(dic3.keys())) #键转换成列表 #>>>[‘name‘, ‘age‘, ‘hobby‘] print(type(dic3.values())) #>>><class ‘dict_values‘> print(list(dic3.values())) #值转换成列表 #>>>[‘alex‘, 18, ‘girl‘] print(list(dic3.items())) #>>>[(‘name‘, ‘alex‘), (‘hobby‘, ‘girl‘), (‘age‘, 18)]
1.5 改
li = [1,2,3,4] li[2] = 5 dic3 = {‘age‘:18,‘name‘:‘alex‘,‘hobby‘:‘girl‘} dic3[‘age‘] = 55 print(dic3) #>>>{‘hobby‘: ‘girl‘, ‘age‘: 55, ‘name‘: ‘alex‘}
1.6 update方法
dic4 = {‘age‘:18,‘name‘:‘alex‘,‘hobby‘:‘girl‘} dic5 = {‘1‘:‘111‘,‘2‘:‘222‘} dic4.update(dic5) print(dic4) #>>>{‘hobby‘: ‘girl‘, ‘age‘: 18, ‘2‘: ‘222‘, ‘name‘: ‘alex‘, ‘1‘: ‘111‘} print(dic5) #>>>{‘1‘: ‘111‘, ‘2‘: ‘222‘}
dic4 = {‘age‘:18,‘name‘:‘alex‘,‘hobby‘:‘girl‘}dic6 = {‘name‘:‘wangba‘}dic4.update(dic6)print(dic4)#>>>{‘hobby‘: ‘girl‘, ‘name‘: ‘wangba‘, ‘age‘: 18}
时间: 2024-10-24 20:17:17