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}")
相关推荐
fanruitian9 小时前
python 可视化 panda seaborn matplotlib.pyplot
开发语言·python·matplotlib
梦想不只是梦与想10 小时前
Python 中的 json 模块
python·json·对象转字符串
星河耀银海10 小时前
Python文件操作:read、readline、readlines读取方式对比
python·文件操作·面向对象·基础函数·教程学习
傅科摆 _ py10 小时前
DP,贪心,堆和栈,二分力扣复习
开发语言·python·算法
吴名氏.11 小时前
Java转AI Agent教程(第一周)让模型先跑起来
人工智能·python·ai·ai agent
第404号工位11 小时前
离职退电脑前别只点“清空回收站”!手把手教你彻底抹除凭证与数字痕迹
linux·python·架构
Metaphor69211 小时前
使用 Python 在 Word 文档中添加、修改和删除变量
python·word
終不似少年遊*12 小时前
【AI Coding实战方法论】从计划协作到架构护栏,一套能长期复用的工程流程
人工智能·python·团队开发·ai编程·ai coding·skills·上下文管理
lusklusklusk12 小时前
Python 全局变量与局部变量区别——global 关键字、__main__ 块与作用域示例
开发语言·前端·python
马剑威(威哥爱编程)12 小时前
Python 智能体开发实战 01:装了三遍环境还在报错?虚拟环境和 DeepSeek 一次配到位
开发语言·人工智能·python·agent