为了账号安全,请及时绑定邮箱和手机立即绑定

Python - 字典3

修改字典项

您可以通过引用其键名来更改特定项的值:

示例,将 “year” 更改为 2018:

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
thisdict["year"] = 2018

更新字典

update() 方法将使用给定参数中的项来更新字典。

参数必须是一个字典,或具有键值对的可迭代对象。

示例,使用 update() 方法来更新车辆的 “year”:

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
thisdict.update({"year": 2020})

Python - 添加字典项

通过使用新的索引键并为其分配一个值,可以向字典中添加项:

示例,向字典中添加一个项目:

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
thisdict["color"] = "red"
print(thisdict)

更新字典

update() 方法将使用给定参数中的项来更新字典。如果该项不存在,则会添加该项。

参数必须是一个字典,或具有键值对的可迭代对象。

示例,使用 update() 方法向字典中添加颜色项:

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
thisdict.update({"color": "red"})

Python - 删除字典项

有几种方法可以从字典中删除项:

示例,pop() 方法会删除具有指定键名的项:

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
thisdict.pop("model")
print(thisdict)

示例,popitem() 方法将删除最后插入的项(在 3.7 之前的版本中,将删除一个随机项):

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
thisdict.popitem()
print(thisdict)

示例,del 关键字会删除具有指定键名的项:

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
del thisdict["model"]
print(thisdict)

示例,del 关键字还可以完全删除字典:

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
del thisdict
print(thisdict) #这将导致错误,因为 "thisdict" 不再存在。

示例,clear() 方法会清空字典:

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
thisdict.clear()
print(thisdict)

Python - 循环遍历字典

您可以使用 for 循环遍历字典。在循环字典时,返回值是字典的键,但也有方法可以返回值。

示例,逐个打印字典中的所有键名:

for x in thisdict:
  print(x)

示例,逐个打印字典中的所有值:

for x in thisdict:
  print(thisdict[x])

示例,您还可以使用 values() 方法返回字典的值:

for x in thisdict.values():
  print(x)

示例,您可以使用 keys() 方法返回字典的键:

for x in thisdict.keys():
  print(x)

示例,通过使用 items() 方法,可以同时循环遍历键和值:

for x, y in thisdict.items():
  print(x, y)
点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消