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}")
相关推荐
布吉岛的石头7 分钟前
Java 程序员第 49 阶段11:Java 接 BERT:用 ONNX Runtime 做句向量推理
java·人工智能·python·深度学习·bert·transformer
第25小时记录10 分钟前
数据结构与算法 -第 3 章 常用算法-动态规划
数据结构·python
Dmz丶14 分钟前
前端转 AI 100 天 Day 18:pytest 入门——为什么你必须要写测试
python
用户0190275816129 分钟前
如何用 Python 计算 DMA 平行线差指标?
python
奈葵1 小时前
Python
开发语言·python
happylifetree1 小时前
Python54-55:核心语法-数据容器-字典dict-案例
python
小小张说故事1 小时前
Python 迭代器和生成器到底啥区别?3 个例子讲透,别再背概念了
python
外收内放1 小时前
Python基础语法练习题(56优化版补充)
开发语言·python
专注API从业者2 小时前
告别复杂页面解析,OpenClaw 快速搭建电商商品监控与数据分析脚本
大数据·数据库·python·数据挖掘·数据分析
王立志_LEO2 小时前
HTTPX 完整用法总结
python