Python - 字典3

打印 上一主题 下一主题

主题 892|帖子 892|积分 2676

修改字典项

您可以通过引用其键名来更改特定项的值:
示例,将 "year" 更改为 2018:
  1. thisdict = {
  2.   "brand": "Ford",
  3.   "model": "Mustang",
  4.   "year": 1964
  5. }
  6. thisdict["year"] = 2018
复制代码
更新字典

update() 方法将使用给定参数中的项来更新字典。
参数必须是一个字典,或具有键值对的可迭代对象。
示例,使用 update() 方法来更新车辆的 "year":
  1. thisdict = {
  2.   "brand": "Ford",
  3.   "model": "Mustang",
  4.   "year": 1964
  5. }
  6. thisdict.update({"year": 2020})
复制代码
Python - 添加字典项

通过使用新的索引键并为其分配一个值,可以向字典中添加项:
示例,向字典中添加一个项目:
  1. thisdict = {
  2.   "brand": "Ford",
  3.   "model": "Mustang",
  4.   "year": 1964
  5. }
  6. thisdict["color"] = "red"
  7. print(thisdict)
复制代码
更新字典

update() 方法将使用给定参数中的项来更新字典。如果该项不存在,则会添加该项。
参数必须是一个字典,或具有键值对的可迭代对象。
示例,使用 update() 方法向字典中添加颜色项:
  1. thisdict = {
  2.   "brand": "Ford",
  3.   "model": "Mustang",
  4.   "year": 1964
  5. }
  6. thisdict.update({"color": "red"})
复制代码
Python - 删除字典项

有几种方法可以从字典中删除项:
示例,pop() 方法会删除具有指定键名的项:
  1. thisdict = {
  2.   "brand": "Ford",
  3.   "model": "Mustang",
  4.   "year": 1964
  5. }
  6. thisdict.pop("model")
  7. print(thisdict)
复制代码
示例,popitem() 方法将删除最后插入的项(在 3.7 之前的版本中,将删除一个随机项):
  1. thisdict = {
  2.   "brand": "Ford",
  3.   "model": "Mustang",
  4.   "year": 1964
  5. }
  6. thisdict.popitem()
  7. print(thisdict)
复制代码
示例,del 关键字会删除具有指定键名的项:
  1. thisdict = {
  2.   "brand": "Ford",
  3.   "model": "Mustang",
  4.   "year": 1964
  5. }
  6. del thisdict["model"]
  7. print(thisdict)
复制代码
示例,del 关键字还可以完全删除字典:
  1. thisdict = {
  2.   "brand": "Ford",
  3.   "model": "Mustang",
  4.   "year": 1964
  5. }
  6. del thisdict
  7. print(thisdict) #这将导致错误,因为 "thisdict" 不再存在。
复制代码
示例,clear() 方法会清空字典:
  1. thisdict = {
  2.   "brand": "Ford",
  3.   "model": "Mustang",
  4.   "year": 1964
  5. }
  6. thisdict.clear()
  7. print(thisdict)
复制代码
Python - 循环遍历字典

您可以使用 for 循环遍历字典。在循环字典时,返回值是字典的键,但也有方法可以返回值。
示例,逐个打印字典中的所有键名:
  1. for x in thisdict:
  2.   print(x)
复制代码
示例,逐个打印字典中的所有值:
  1. for x in thisdict:
  2.   print(thisdict[x])
复制代码
示例,您还可以使用 values() 方法返回字典的值:
  1. for x in thisdict.values():
  2.   print(x)
复制代码
示例,您可以使用 keys() 方法返回字典的键:
  1. for x in thisdict.keys():
  2.   print(x)
复制代码
示例,通过使用 items() 方法,可以同时循环遍历键和值:
  1. for x, y in thisdict.items():
  2.   print(x, y)
复制代码
最后

为了方便其他设备和平台的小伙伴观看往期文章,链接奉上:
公众号搜索Let us Coding阿里开发者社区InfoQCSDN腾讯开发者社区思否51CTO掘金helloworld慕课博客园
看完如果觉得有帮助,欢迎点赞、收藏关注

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

九天猎人

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表