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}")
相关推荐
岁月宁静6 小时前
五、《从零手撸 Agent》 — 什么是 Agent:从“会聊天”到“会做事”,差的就是一个循环
python·agent
梯度下降者6 小时前
Python - 函数
python·高阶函数·可调用对象·functools·嵌套作用域
starzy19908 小时前
深入理解Scala隐式参数:上下文流转
开发语言·python·scala
wuyk5559 小时前
Spider-第16讲-线程池与竞态问题
大数据·爬虫·python·elasticsearch·搜索引擎
kyle~15 小时前
FastAPI --- 将业务能力以 API 的形式提供给外部系统
python·fastapi·前后端
aiotto资源分享15 小时前
Python 写 JSON 文件,程序中途退出会留下什么?
java·python·json·jsondecodeerror
梯度下降者16 小时前
Python信号量,条件变量,事件学习
python·条件变量·事件·信号量·线程通信
MSTcheng.17 小时前
【AI应用实战】用 FastAPI + SSE 做一个自己的 AI 聊天网页:流式输出、多轮对话与完整源码
人工智能·python·大模型·fastapi·sse·ai聊天助手
the局外人18 小时前
Python 实战检索优化:BM25、向量与重排
数据库·后端·python
__underline__18 小时前
冷门Python知识点006篇:Python 类体里的名字,能被"凭空造出来"
后端·python