成都创新互联网站制作重庆分公司

python更新字典的方法

这篇文章将为大家详细讲解有关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更新字典的方法
分享链接:http://cxhlcq.com/article/pjeisi.html

其他资讯

在线咨询

微信咨询

电话咨询

028-86922220(工作日)

18980820575(7×24)

提交需求

返回顶部