Python 字典 update() 方法

原创
2018/01/20 23:07
阅读数 369

描述

Python 字典 update() 方法用于更新字典中的键/值对,可以修改存在的键对应的值,也可以添加新的键/值对到字典中。

用法与 Python dict() 函数相似。

语法

update() 方法语法:

1

D.update(key/value)

参数

  • key/value -- 用于更新字典的键/值对,此处可以表示键/值对的方法有很多,请看实例。

返回值

该方法没有任何返回值。

实例

以下实例展示了 update() 方法的使用方法:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

# !/usr/bin/python3

 

= {'one':1,'two':2}

 

D.update({'three':3,'four':4})  # 传一个字典

print(D)

 

D.update(five=5,six=6)  # 传关键字

print(D)

 

D.update([('seven',7),('eight',8)])  # 传一个包含一个或多个元祖的列表

print(D)

 

D.update((['nice',9],['ten',10]))  # 传一个包含一个或多个列表的元祖

print(D)

 

D.update(zip(['eleven','twelve'],[11,12]))  # 传一个zip()函数

print(D)

 

D.update(one=111,two=222)  # 使用以上任意方法修改存在的键对应的值

print(D)

以上实例输出结果为:

1

2

3

4

5

6

{'one'1'four'4'three'3'two'2}

{'one'1'four'4'three'3'five'5'two'2'six'6}

{'seven'7'one'1'four'4'three'3'five'5'two'2'six'6'eight'8}

{'seven'7'one'1'four'4'three'3'ten'10'five'5'nice'9'two'2'six'6'eight'8}

{'one'1'four'4'three'3'twelve'12'ten'10'seven'7'six'6'eleven'11'two'2'nice'9'five'5'eight'8}

{'one'111'four'4'three'3'twelve'12'ten'10'seven'7'six'6'eleven'11'two'222'nice'9'five'5'eight'8}

展开阅读全文
加载中

作者的其它热门文章

打赏
0
1 收藏
分享
打赏
0 评论
1 收藏
0
分享
返回顶部
顶部