本文摘自php中文网,作者爱喝马黛茶的安东尼,侵删。
python字典如何改变键值对?相关推荐:《python视频》

修改字典
向字典添加新内容的方法是增加新的键/值对,修改或删除已有键/值对如下实例:
1 2 3 4 5 6 7 | 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 | >> > 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到当前字典
1 2 3 4 5 6 7 8 | >>> a
{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字典改变键值对的方法的详细内容,更多文章请关注木庄网络博客!!
相关阅读 >>
怎么在cmd运行Python
Python中整数的最大可能值是多少?(代码示例)
Python怎么将整数反转输出
如何改变 matplotlib 图像大小
总结用Python 操作 pdf 的几种方法
Python实现输出带颜色的字符串案例分析
Python判断两个list是否是父子集关系的实例
Python中property函数的用法
Python递归函数,二分查找算法简介
Python包和logging日志的相关介绍
更多相关阅读请进入《Python》频道 >>
人民邮电出版社
python入门书籍,非常畅销,超高好评,python官方公认好书。
转载请注明出处:木庄网络博客 » python字典改变键值对的方法