本文摘自php中文网,作者乌拉乌拉~,侵删。
今天这篇文章中我们来了解一下python之中的字典,在这文章之中我会对python字典修改进行说明,以及举例说明如何修改python字典内的值。废话不多说,我们开始进入文章吧。首先我们得知道什么是修改字典
修改字典
向字典添加新内容的方法是增加新的键/值对,修改或删除已有键/值对如下实例:
1 2 3 4 5 6 7 8 9 | # !/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.字典中的键存在时,可以通过字典名+下标的方式访问字典中改键对应的值,若键不存在则会抛出异常。如果想直接向字典中添加元素可以直接用字典名+下标+值的方式添加字典元素,只写键想后期对键赋值这种方式会抛出异常。
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' }
|
2.使用updata方法,把字典中有相应键的键值对添加update到当前字典>>> a
阅读剩余部分
相关阅读 >>
Python close()是什么?Python close()定义及用法详解
Python遍历输出列表中最长的单词
Python中关于input和raw_input的比较
Python把二维数组输出为图片的方法
怎么在电脑上下载Python
Python 如何运行文件
Python使用正则表达式实现搜索单词的示例代码
Python path怎么设置
Python中end=' '是什么意思
Python画圆运用了什么函数
更多相关阅读请进入《Python》频道 >>
人民邮电出版社
python入门书籍,非常畅销,超高好评,python官方公认好书。
转载请注明出处:木庄网络博客 » 如何修改python字典内的值?2种修改python字典内的值方法总结