day06_06 字典操作01
阿新 • • 發佈:2017-09-09
返回 print 1.4 blog 值轉換 span update ems value
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}
day06_06 字典操作01