1、字典中的键存在时,可以通过字典名+下标的方式访问字典中改键对应的值,若键不存在则会抛出异常。如果想直接向字典中添加元素可以直接用字典名+下标+值的方式添加字典元素,只写键想后期对键赋值这种方式会抛出异常。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
>>>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到当前字典
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
>>> 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字典元素的添加与修改方法详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/eacxzm/article/details/79894225