Skip to content

第10章:字典与集合操作

10.1 字典(dict,键值对容器,高频)

字典是Python中非常重要的数据结构,它以键值对(key-value)的形式存储数据。字典是无序的、可变的,键必须是唯一的且不可变的(如字符串、数字、元组)。

字典创建

  • 语法:使用花括号{}创建字典
  • 示例
    python
    # 创建空字典
    empty_dict = {}
    
    # 创建包含键值对的字典
    person = {"name": "zhangsan", "age": 18, "gender": "男"}
    
    # 使用dict()函数创建字典
    dict_from_list = dict([("name", "zhangsan"), ("age", 18)])
    dict_from_kwargs = dict(name="zhangsan", age=18)

字典访问

  • 语法:通过键(key)访问值(value)
  • 示例
    python
    person = {"name": "zhangsan", "age": 18, "gender": "男"}
    print(person["name"])  # 输出:zhangsan
    print(person["age"])   # 输出:18
    
    # 使用get()方法访问(推荐,避免键不存在的错误)
    print(person.get("name"))     # 输出:zhangsan
    print(person.get("address"))  # 输出:None
    print(person.get("address", "未知"))  # 输出:未知

字典增删改

  • 修改值:通过键直接赋值

    python
    person = {"name": "zhangsan", "age": 18}
    person["age"] = 19
    print(person)  # 输出:{'name': 'zhangsan', 'age': 19}
  • 添加键值对:通过新键赋值

    python
    person = {"name": "zhangsan", "age": 18}
    person["gender"] = "男"
    person["phone"] = "123456"
    print(person)  # 输出:{'name': 'zhangsan', 'age': 18, 'gender': '男', 'phone': '123456'}
  • 删除键值对

    • del:删除指定键的键值对
    • pop():删除指定键的键值对并返回值
    • popitem():删除最后一个键值对并返回
    • 示例:
      python
      person = {"name": "zhangsan", "age": 18, "gender": "男"}
      del person["gender"]  # 删除指定键
      print(person)  # 输出:{'name': 'zhangsan', 'age': 18}
      
      age = person.pop("age")  # 删除并返回值
      print(age)  # 输出:18
      print(person)  # 输出:{'name': 'zhangsan'}

字典常用方法

  • keys():返回所有键的视图对象
  • values():返回所有值的视图对象
  • items():返回所有键值对的视图对象
  • 示例
    python
    person = {"name": "zhangsan", "age": 18, "gender": "男"}
    
    print("键:", list(person.keys()))  # 输出:键: ['name', 'age', 'gender']
    print("值:", list(person.values()))  # 输出:值: ['zhangsan', 18, '男']
    print("键值对:", list(person.items()))  # 输出:键值对: [('name', 'zhangsan'), ('age', 18), ('gender', '男')]
    
    # 遍历字典
    print("\n遍历键:")
    for key in person:
        print(key)
    
    print("\n遍历键值对:")
    for key, value in person.items():
        print(f"{key}: {value}")

10.2 集合(set,去重容器)

集合是一种无序、不可重复的数据结构,适合用于去重和集合运算。

集合创建

  • 语法:使用花括号{}set()函数创建集合
  • 示例
    python
    # 创建空集合(注意:{}创建的是空字典,不是空集合)
    empty_set = set()
    
    # 创建包含元素的集合(自动去重)
    numbers = {1, 2, 3, 3, 4, 5, 5}
    print(numbers)  # 输出:{1, 2, 3, 4, 5}
    
    # 使用set()函数创建集合
    set_from_string = set("hello")  # {'h', 'e', 'l', 'o'}
    set_from_list = set([1, 2, 2, 3])  # {1, 2, 3}

集合常用操作

  • 添加元素

    • add():添加单个元素
    • update():添加多个元素
    • 示例:
      python
      s = {1, 2, 3}
      s.add(4)  # 添加单个元素
      print(s)  # 输出:{1, 2, 3, 4}
      
      s.update([5, 6, 7])  # 添加多个元素
      print(s)  # 输出:{1, 2, 3, 4, 5, 6, 7}
  • 删除元素

    • remove():删除指定元素(元素不存在会报错)
    • discard():删除指定元素(元素不存在不会报错)
    • pop():删除并返回任意元素
    • 示例:
      python
      s = {1, 2, 3, 4, 5}
      s.remove(3)  # 删除指定元素
      print(s)  # 输出:{1, 2, 4, 5}
      
      s.discard(10)  # 删除不存在的元素,不会报错
      print(s)  # 输出:{1, 2, 4, 5}
      
      removed = s.pop()  # 删除并返回任意元素
      print(removed)  # 输出:1
      print(s)  # 输出:{2, 4, 5}
  • 集合运算

    • 交集(&):两个集合的公共元素
    • 并集(|):两个集合的所有元素
    • 差集(-):第一个集合有而第二个集合没有的元素
    • 对称差集(^):两个集合中不同时存在的元素
    • 示例:
      python
      a = {1, 2, 3, 4, 5}
      b = {4, 5, 6, 7, 8}
      
      print("交集:", a & b)  # 输出:交集: {4, 5}
      print("并集:", a | b)  # 输出:并集: {1, 2, 3, 4, 5, 6, 7, 8}
      print("差集:", a - b)  # 输出:差集: {1, 2, 3}
      print("对称差集:", a ^ b)  # 输出:对称差集: {1, 2, 3, 6, 7, 8}

集合特点

  • 无序:集合中的元素没有固定顺序
  • 不可重复:集合中的元素唯一,自动去重
  • 元素必须是不可变类型:集合中的元素必须是不可变的,如字符串、数字、元组
  • 适合场景:去重、集合运算(如共同好友查询)

实操案例:用户信息管理(用字典存储)

案例:用户信息管理

python
"""
用户信息管理
功能:使用字典存储和管理用户信息
"""

# 初始化用户字典
users = {
    "user1": {"name": "张三", "age": 18, "email": "zhangsan@example.com"},
    "user2": {"name": "李四", "age": 20, "email": "lisi@example.com"},
    "user3": {"name": "王五", "age": 22, "email": "wangwu@example.com"}
}

# 打印用户信息
def print_users():
    print("\n=== 用户信息 ===")
    for user_id, user_info in users.items():
        print(f"用户ID: {user_id}")
        print(f"  姓名: {user_info['name']}")
        print(f"  年龄: {user_info['age']}")
        print(f"  邮箱: {user_info['email']}")
    print("================\n")

# 添加用户
def add_user():
    user_id = input("请输入用户ID:")
    if user_id in users:
        print("用户ID已存在!")
        return
    
    name = input("请输入姓名:")
    age = int(input("请输入年龄:"))
    email = input("请输入邮箱:")
    
    users[user_id] = {"name": name, "age": age, "email": email}
    print("用户添加成功!")

# 修改用户信息
def update_user():
    user_id = input("请输入要修改的用户ID:")
    if user_id not in users:
        print("用户ID不存在!")
        return
    
    user_info = users[user_id]
    print(f"当前用户信息:")
    print(f"  姓名: {user_info['name']}")
    print(f"  年龄: {user_info['age']}")
    print(f"  邮箱: {user_info['email']}")
    
    name = input("请输入新姓名(按回车保持不变):")
    age = input("请输入新年龄(按回车保持不变):")
    email = input("请输入新邮箱(按回车保持不变):")
    
    if name:
        user_info['name'] = name
    if age:
        user_info['age'] = int(age)
    if email:
        user_info['email'] = email
    
    print("用户信息修改成功!")

# 删除用户
def delete_user():
    user_id = input("请输入要删除的用户ID:")
    if user_id in users:
        del users[user_id]
        print("用户删除成功!")
    else:
        print("用户ID不存在!")

# 主菜单
def main():
    while True:
        print("\n用户信息管理系统")
        print("1. 查看用户信息")
        print("2. 添加用户")
        print("3. 修改用户信息")
        print("4. 删除用户")
        print("5. 退出")
        
        choice = input("请输入选择:")
        
        if choice == "1":
            print_users()
        elif choice == "2":
            add_user()
        elif choice == "3":
            update_user()
        elif choice == "4":
            delete_user()
        elif choice == "5":
            print("退出系统!")
            break
        else:
            print("输入错误,请重新输入!")

if __name__ == "__main__":
    main()

运行结果

用户信息管理系统
1. 查看用户信息
2. 添加用户
3. 修改用户信息
4. 删除用户
5. 退出
请输入选择:1

=== 用户信息 ===
用户ID: user1
  姓名: 张三
  年龄: 18
  邮箱: zhangsan@example.com
用户ID: user2
  姓名: 李四
  年龄: 20
  邮箱: lisi@example.com
用户ID: user3
  姓名: 王五
  年龄: 22
  邮箱: wangwu@example.com
================

用户信息管理系统
1. 查看用户信息
2. 添加用户
3. 修改用户信息
4. 删除用户
5. 退出
请输入选择:2
请输入用户ID:user4
请输入姓名:赵六
请输入年龄:25
请输入邮箱:zhaoliu@example.com
用户添加成功!

用户信息管理系统
1. 查看用户信息
2. 添加用户
3. 修改用户信息
4. 删除用户
5. 退出
请输入选择:1

=== 用户信息 ===
用户ID: user1
  姓名: 张三
  年龄: 18
  邮箱: zhangsan@example.com
用户ID: user2
  姓名: 李四
  年龄: 20
  邮箱: lisi@example.com
用户ID: user3
  姓名: 王五
  年龄: 22
  邮箱: wangwu@example.com
用户ID: user4
  姓名: 赵六
  年龄: 25
  邮箱: zhaoliu@example.com
================

实操案例:列表去重(用集合)

案例:列表去重

python
"""
列表去重
功能:使用集合对列表进行去重
"""

# 原始列表(包含重复元素)
original_list = [1, 2, 3, 2, 4, 3, 5, 4, 6, 5]
print(f"原始列表:{original_list}")

# 使用集合去重
unique_list = list(set(original_list))
print(f"去重后:{unique_list}")

# 保持原始顺序的去重方法
def unique_preserve_order(lst):
    seen = set()
    result = []
    for item in lst:
        if item not in seen:
            seen.add(item)
            result.append(item)
    return result

ordered_unique_list = unique_preserve_order(original_list)
print(f"保持顺序的去重后:{ordered_unique_list}")

# 字符串列表去重
string_list = ["apple", "banana", "apple", "cherry", "banana", "orange"]
print(f"\n原始字符串列表:{string_list}")
unique_strings = list(set(string_list))
print(f"去重后:{unique_strings}")

运行结果

原始列表:[1, 2, 3, 2, 4, 3, 5, 4, 6, 5]
去重后:[1, 2, 3, 4, 5, 6]
保持顺序的去重后:[1, 2, 3, 4, 5, 6]

原始字符串列表:['apple', 'banana', 'apple', 'cherry', 'banana', 'orange']
去重后:['cherry', 'apple', 'banana', 'orange']

实操案例:集合运算(如共同好友查询)

案例:共同好友查询

python
"""
共同好友查询
功能:使用集合运算查找共同好友
"""

# 定义用户的好友列表
user_friends = {
    "张三": {"李四", "王五", "赵六", "钱七"},
    "李四": {"张三", "王五", "孙八", "周九"},
    "王五": {"张三", "李四", "赵六", "孙八"},
    "赵六": {"张三", "王五", "周九", "吴十"}
}

# 打印用户的好友列表
print("各用户的好友列表:")
for user, friends in user_friends.items():
    print(f"{user}的好友:{friends}")

# 查询两个用户的共同好友
def find_common_friends(user1, user2):
    if user1 not in user_friends or user2 not in user_friends:
        return f"用户{user1}{user2}不存在!"
    
    common = user_friends[user1] & user_friends[user2]
    if common:
        return f"{user1}{user2}的共同好友:{common}"
    else:
        return f"{user1}{user2}没有共同好友!"

# 测试共同好友查询
print("\n共同好友查询:")
print(find_common_friends("张三", "李四"))
print(find_common_friends("张三", "赵六"))
print(find_common_friends("李四", "赵六"))

# 查询用户的独有的好友
def find_unique_friends(user1, user2):
    if user1 not in user_friends or user2 not in user_friends:
        return f"用户{user1}{user2}不存在!"
    
    unique = user_friends[user1] - user_friends[user2]
    if unique:
        return f"{user1}独有的好友:{unique}"
    else:
        return f"{user1}没有独有的好友!"

print("\n独有好友查询:")
print(find_unique_friends("张三", "李四"))
print(find_unique_friends("李四", "张三"))

运行结果

各用户的好友列表:
张三的好友:{'赵六', '李四', '钱七', '王五'}
李四的好友:{'孙八', '张三', '周九', '王五'}
王五的好友:{'赵六', '孙八', '张三', '李四'}
赵六的好友:{'吴十', '张三', '周九', '王五'}

共同好友查询:
张三和李四的共同好友:{'王五'}
张三和赵六的共同好友:{'王五'}
李四和赵六的共同好友:set()

独有好友查询:
张三独有的好友:{'钱七', '赵六'}
李四独有的好友:{'孙八', '周九'}

新手易错点

  • 字典访问不存在的键:直接访问不存在的键会导致错误

    python
    person = {"name": "zhangsan", "age": 18}
    print(person["address"])  # 错误:KeyError: 'address'
    
    # 正确:使用get()方法
    print(person.get("address"))  # 输出:None
  • 集合无序导致索引访问报错:集合是无序的,不能通过索引访问

    python
    s = {1, 2, 3}
    print(s[0])  # 错误:'set' object does not support indexing
  • 集合元素必须是不可变类型:集合中的元素必须是不可变的

    python
    s = {1, 2, [3, 4]}  # 错误:unhashable type: 'list'
    
    # 正确:使用元组
    s = {1, 2, (3, 4)}  # 正确

通过本章的学习,你已经掌握了Python中字典和集合的基本操作。字典是键值对容器,适合存储关联数据;集合是无序、不可重复的容器,适合去重和集合运算。在实际编程中,你会根据具体需求选择合适的数据结构。

© 2026 编程马·菜鸟教程 版权所有