python字典改变键值对的方法


本文摘自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字典改变键值对的方法的详细内容,更多文章请关注木庄网络博客!!

相关阅读 >>

Python中记录循环次数的方法

Python怎么判断数据类型

Python中dict是什么

Python 是什么?

Python装饰器以什么开头

Python的gui有哪些

编程Python是什么

Python实现决策树算法

实例详解Python人脸识别

Python如何判断一个字符串是否包含指定子字符串

更多相关阅读请进入《Python》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...