栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python如何更新字典?

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python如何更新字典?

python中可以使用update()函数更新字典。

update()方法语法:

dict.update(dict2)
D.update(key/value)

参数

dict2 -- 添加到指定字典dict里的字典。

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

示例:

1、字典dict2的键/值对更新到dict里

#!/usr/bin/python

dict = {'Name': 'Zara', 'Age': 7}
dict2 = {'Sex': 'female' }

dict.update(dict2)
print "Value : %s" %  dict

输出结果:

Value : {'Age': 7, 'Name': 'Zara', 'Sex': 'female'}

2、更新字典中的键值对

# !/usr/bin/python3
 
D = {'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(zip(['eleven', 'twelve'], [11, 12]))  # 传一个zip()函数
print(D)
 
D.update(one=111, two=222)  # 使用以上任意方法修改存在的键对应的值
print(D)

输出结果:

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

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

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

{'one': 1, 'eight': 8, 'seven': 7, 'four': 4, 'eleven': 11, 'six': 6, 'twelve': 12, 'two': 2, 'five': 5, 'three': 3}

{'four': 4, 'seven': 7, 'twelve': 12, 'six': 6, 'eleven': 11, 'three': 3, 'one': 111, 'eight': 8, 'two': 222, 'five': 5}

更多Python知识请关注Python自学网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/806405.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号