Python - 字典3

修改字典项

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

示例,将 "year" 更改为 2018:

python 复制代码
thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
thisdict["year"] = 2018

更新字典

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

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

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

python 复制代码
thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
thisdict.update({"year": 2020})

Python - 添加字典项

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

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

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

更新字典

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

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

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

python 复制代码
thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
thisdict.update({"color": "red"})

Python - 删除字典项

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

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

python 复制代码
thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
thisdict.pop("model")
print(thisdict)

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

python 复制代码
thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
thisdict.popitem()
print(thisdict)

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

python 复制代码
thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
del thisdict["model"]
print(thisdict)

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

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

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

python 复制代码
thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
thisdict.clear()
print(thisdict)

Python - 循环遍历字典

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

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

python 复制代码
for x in thisdict:
  print(x)

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

python 复制代码
for x in thisdict:
  print(thisdict[x])

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

python 复制代码
for x in thisdict.values():
  print(x)

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

python 复制代码
for x in thisdict.keys():
  print(x)

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

python 复制代码
for x, y in thisdict.items():
  print(x, y)

最后

为了方便其他设备和平台的小伙伴观看往期文章,链接奉上:

公众号搜索Let us Coding 阿里开发者社区 InfoQ CSDN 腾讯开发者社区 思否 51CTO 掘金 helloworld 慕课 博客园

看完如果觉得有帮助,欢迎点赞、收藏关注

相关推荐
人工干智能1 分钟前
科普:<generator object ...>,不是报错!兼谈[x for x in ...]与(x for x in ...)
python
白露与泡影1 分钟前
Spring Boot 中Servlet、Filter、Listener 四种注册方式全解析
spring boot·后端·servlet
张二娃同学1 分钟前
基于 Python 与 Tkinter 的猜数字游戏设计与实现:支持玩家猜数与 AI 反向推理
开发语言·git·python·游戏·开源
ooseabiscuit3 分钟前
springboot下使用druid-spring-boot-starter
java·spring boot·后端
zzwq.4 分钟前
单例模式:Python中实现单例的几种方式
python
霸道流氓气质5 分钟前
SpringBoot集成Neo4j入门流程及示例代码
spring boot·后端·neo4j
致宏Rex7 分钟前
uv 教程:安装、常用命令、项目结构与关键文件
python·pip·uv
Circ.14 分钟前
wsl部署deerflow实现调用自定义的skill(demo级别调用)
python·大模型·deerflow
郝学胜-神的一滴16 分钟前
PyTorch张量维度操控:transpose与permute深度拆解与实战指南
人工智能·pytorch·python·深度学习·算法·机器学习
弹简特20 分钟前
【JavaEE25-后端部分】从“统一回执单”到“统一投诉处理”:Spring Boot 轻松搞定统一返回格式和统一异常处理
java·spring boot·后端·统一返回格式·统一异常