• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

python如何更新字典?

python 搞java代码 3年前 (2022-05-21) 21次浏览 已收录 0个评论

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

update()方法语法:

<a href="https://www.gaodaima.com/tag/dict" title="查看更多关于dict的文章" target="_blank">dict</a>.update(dict2)

www#gaodaima.com来源gao@!dai!ma.com搞$$代^@码!网搞代码

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知识请关注搞代码网。

来源:搞代码网:原文地址:https://www.gaodaima.com


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:python如何更新字典?

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址