字典 dict:键值对与增删改查

文章顶部广告位
728×90 或 336×280

一、引言

字典存储键值对!通过键快速查找值!非常常用!

💡 字典就像一本字典,查"键"找"值"!

二、创建字典

# 基本语法
person = {
    "name": "张三",
    "age": 25,
    "city": "北京"
}

# 空字典
empty = {}

# 另一种方式
person2 = dict(name="李四", age=30)

三、访问值

person = {"name": "张三", "age": 25, "city": "北京"}

# 1. 用 [](如果键不存在会报错)
print(person["name"])  # 张三

# 2. 用 get()(更安全,不存在返回 None 或默认值
print(person.get("age"))  # 25
print(person.get("email", "无"))  # 无(默认值)

四、添加和修改

person = {"name": "张三", "age": 25}

# 添加(键不存在就是添加
person["email"] = "zhangsan@example.com"
print(person)

# 修改(键存在就是修改
person["age"] = 26
print(person)

# 用 update() 批量更新
person.update({"city": "北京", "phone": "123456"})
print(person)

五、删除

person = {"name": "张三", "age": 25, "city": "北京"}

# 1. del
del person["city"]
print(person)

# 2. pop()(删除并返回)
age = person.pop("age")
print(age)
print(person)

# 3. popitem()(删除最后一个,返回键值对)
last = person.popitem()
print(last)

# 4. clear()(清空)
person.clear()
print(person)

六、常用操作

person = {"name": "张三", "age": 25, "city": "北京"}

# 获取所有键
print(person.keys())

# 获取所有值
print(person.values())

# 获取所有键值对
print(person.items())

# 遍历字典
for key, value in person.items():
    print(f"{key}: {value}")

# 检查键是否存在
print("name" in person)  # True
print("email" in person)  # False

七、字典的键的要求

# 键必须是不可变类型!
# ✅ 可以用:字符串、数字、元组
# ❌ 不可以用:列表、字典

good_dict = {
    "name": "张三",  # 字符串
    123: "数字",    # 数字
    (1, 2): "元组"   # 元组
}

# bad_dict = {
#     [1, 2]: "不行"  # 列表不行!
# }

八、实际例子

# 1. 词频统计
text = "hello hello world python python python"
words = text.split()
count = {}
for word in words:
    if word in count:
        count[word] += 1
    else:
        count[word] = 1
print(count)

# 2. 用户信息
user = {
    "username": "admin",
    "password": "123456",
    "friends": ["张三", "李四"],
    "info": {"age": 25, "city": "北京"}
}

九、课后练习题

# 练习 1:创建一个字典存储学生的个人信息
# 练习 2:统计一段文字中每个单词出现的次数
# 练习 3:遍历字典并打印所有键和值

总结

通过本章学习,你应该已经掌握了「字典 dict:键值对与增删改查」的相关知识。

字典很强大!下一章学习集合!

文章中间广告位
600×300 或 300×250
← 上一篇 下一篇 →
文章底部广告位
728×90 或 300×250