Python017-第二章15.数据容器-dict常用操作

字典dict-常用操作

python 复制代码
# -------- 字典 常见操作------------
dict1 = {"王林":670, "李慕婉":608, "许立国":580, "韩立":688}
print(dict1)

# 添加 - key不存在就是添加
dict1["涛哥"] = 550
print(dict1)    # {'王林': 670, '李慕婉': 608, '许立国': 580, '韩立': 688, '涛哥': 550}

# 修改 - key存在就是修改
dict1["涛哥"] = 620
print(dict1)    # {'王林': 670, '李慕婉': 608, '许立国': 580, '韩立': 688, '涛哥': 620}

# 查询
print(dict1["涛哥"])  # 620
print(dict1.get("涛哥"))  # 620

# 获取的值封装到字典独有的数据类型中
print(dict1.keys()) # dict_keys(['王林', '李慕婉', '许立国', '韩立', '涛哥'])
print(dict1.values())   # dict_values([670, 608, 580, 688, 620])
print(dict1.items())    # dict_items([('王林', 670), ('李慕婉', 608), ('许立国', 580), ('韩立', 688), ('涛哥', 620)])

# 删除
score = dict1.pop("许立国")
print(score)    # 580
print(dict1)    # {'王林': 670, '李慕婉': 608, '韩立': 688, '涛哥': 620}

del dict1 ["韩立"]
print(dict1)    # {'王林': 670, '李慕婉': 608, '涛哥': 620}

# 遍历(以下三种方式效果一样)
for k in dict1.keys():
    print(f"{k}: {dict1[k]}")

for item in dict1.items():
    print(f"{item[0]}: {item[1]}")

for k, v in dict1.items():  # 解包
    print(f"{k}: {v}")
相关推荐
天佑木枫1 小时前
15天Python入门系列 · 序
开发语言·python
装不满的克莱因瓶1 小时前
了解 LangChain 中的 LLM 与 ChatModel 的差异
人工智能·python·ai·langchain·llm·agent·chatmodel
IT知识分享2 小时前
从零开发在线简繁转换工具:OpenCC 实战、避坑经验与方案选型
javascript·python
lunzi_08262 小时前
【学习笔记】《Python编程 从入门到实践》第8章:函数定义、参数传递与模块导入
笔记·python·学习
杨运交2 小时前
[030][Web模块]Spring Boot 验证与 OpenAPI 集成实战:从校验规则到文档生成
前端·spring boot·python
培培说证2 小时前
2026财务岗位如何快速提升自身能力
python
努力攻坚操作系统3 小时前
编程语言编译运行机制对比:C / Java / Python
java·c语言·python
godspeed_lucip3 小时前
LLM和Agent——专题6:Multi Agent 入门(5)
人工智能·python