python中字典的值是可以被修改的,首先我們得知道什么是修改字典
修改字典
向字典添加新內容的方法是增加新的鍵/值對,修改或刪除已有鍵/值對如下實例:
1
2
3
4
5
6
|
# !/usr/bin/python dict = { 'Name' : 'Zara' , 'Age' : 7 , 'Class' : 'First' }; dict [ 'Age' ] = 8 ; # update existing entry dict [ 'School' ] = "DPS School" ; # Add new entry print "dict['Age']: " , dict [ 'Age' ]; print "dict['School']: " , dict [ 'School' ]; |
以上實例輸出結果:
1
2
|
dict [ 'Age' ]: 8 dict [ 'School' ]: DPS School |
字典中的鍵存在時,可以通過字典名+下標的方式訪問字典中改鍵對應的值,若鍵不存在則會拋出異常。如果想直接向字典中添加元素可以直接用字典名+下標+值的方式添加字典元素,只寫鍵想后期對鍵賦值這種方式會拋出異常。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
>> > a = [ 'apple' , 'banana' , 'pear' , 'orange' ] >> > a [ 'apple' , 'banana' , 'pear' , 'orange' ] >> > a = { 1 : 'apple' , 2 : 'banana' , 3 : 'pear' , 4 : 'orange' } >> > a { 1 : 'apple' , 2 : 'banana' , 3 : 'pear' , 4 : 'orange' } >> > a[ 2 ] 'banana' >> > a[ 5 ] Traceback(most recent call last): File "<pyshell#31>" , line 1 , in < module > a[ 5 ] KeyError: 5 >> > a[ 6 ] = 'grap' >> > a { 1 : 'apple' , 2 : 'banana' , 3 : 'pear' , 4 : 'orange' , 6 : 'grap' } |
實例擴展:
使用updata方法,把字典中有相應鍵的鍵值對添加update到當前字典>>> a
1
2
3
4
5
6
7
|
{ 1 : 'apple' , 2 : 'banana' , 3 : 'pear' , 4 : 'orange' , 6 : 'grap' } >>>a.items() dict_items([( 1 , 'apple' ), ( 2 , 'banana' ), ( 3 , 'pear' ), ( 4 , 'orange' ), ( 6 , 'grap' )]) >>>a.update({ 1 : 10 , 2 : 20 }) >>> a { 1 : 10 , 2 : 20 , 3 : 'pear' , 4 : 'orange' , 6 : 'grap' } #{1:10,2:20}替換了{1: 'apple', 2: 'banana'} |
到此這篇關于python字典的值可以修改嗎的文章就介紹到這了,更多相關python字典的值是否可以更改內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://www.py.cn/faq/python/13165.html