有很多同学问小编python有什么方法可以更新字典,那么今天小编就通过这篇文章来给大家详细解答一下。其实我们在python中可以使用update()函数更新字典。
我们先来看一下update()方法的语法:
dict.update(dict2)
D.update(key/value)
参数:dict2 -- 添加到指定字典dict里的字典。
Key或value的描述:它们是用于更新字典的键or值对,用法与python函数相似,此处可以表示键or值对的方法有很多,我们接下来一起看看实例。
(一)实现字典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'}
(二)更新字典中的键值对
# !/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相关文章请访问分类:python
【版权声明】本文图文出自大盘站@dapan.cc,转载请注明出处!