方法一:方括號[]法
## 修改字典中的鍵值對 dic1 = {'1':'node1','2':'node2'} dic1['1'] = 'hello' print(dic1) # {'1': 'hello', '2': 'node2'} ## 新增字典中的鍵值對 dic1 = {'1':'node1','2':'node2'} dic1['3'] = 'hello' print(dic1) # {'1': 'node1', '2': 'node2', '3': 'hello'}
dic1['key'] = 值,即可用于修改字典中的鍵值對,又可用于新增字典中的鍵值對。
當(dāng)鍵存在時,為修改。
當(dāng)鍵不存在時,為新增。
方法二:dic1.update(dic2)
## 修改字典中的鍵值對 dic1 = {'1':'node1','2':'node2'} dic1.update({'1':'hello'}) print(dic1) # {'1': 'hello', '2': 'node2'} ## 新增字典中的鍵值對 dic1 = {'1':'node1','2':'node2'} dic1.update({'3':'hello'}) print(dic1) # {'1': 'node1', '2': 'node2', '3': 'hello'}
dic1.update(dic2)既可用于修改字典中的鍵值對,又可用于新增字典中的鍵值對。
當(dāng)dic2中有鍵與dic1中鍵沖突時,會修改dic1中的鍵所對應(yīng)的值,即用dic2中沖突鍵的值去覆蓋dic1中的沖突鍵的值。
當(dāng)dic2中的鍵不與dic1中鍵沖突時,則會在dic1中新增dic2中的鍵值對。
1、萬能的方括號[],如果dic['key']單獨(dú)使用,則是獲取鍵所對應(yīng)的值,如果dic['key'] = 值,則根據(jù)鍵存在與否,可以修改鍵所對應(yīng)的值,也可以新增鍵值對。
2、使用第一種方法,方括號[]法比較方便,update方法也比較方便。文章來源:http://www.zghlxwxcb.cn/news/detail-503875.html
3、注意,在使用時不小心經(jīng)常犯下面的錯誤:注意student.get('score')是獲取的值,是表達(dá)式,不能作為左值。文章來源地址http://www.zghlxwxcb.cn/news/detail-503875.html
student = {'id':'001', 'name':'jack', 'score':{}} student.get('score') = {'Chinese':90, 'Math':100, 'English':87} # 相當(dāng)于{} = {'Chinese':90, 'Math':100, 'English':87},肯定不對
到了這里,關(guān)于python中修改和新增字典中鍵值對的兩種方法的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!