字典(Dictionary)

在 Python 中,字典是一种通过键(而非索引)来访问的无序值集合。字典的键必须是可哈希的:例如整数、浮点数、字符串、元组和冻结集合是可哈希的。而列表、字典和除冻结集合外的集合则是不可哈希的。字典从 Python 1.4 开始就被引入。

概述

Python 中字典的基本用法:

dict1 = {}                    # 创建空字典
dict2 = dict()                # 创建空字典 2
dict2 = {"r": 34, "i": 56}    # 初始化为非空值
dict3 = dict([("r", 34), ("i", 56)])  # 从元组列表初始化
dict4 = dict(r=34, i=56)      # 初始化为非空值 3
dict1["temperature"] = 32     # 给键赋值
if "temperature" in dict1:    # 键是否存在的成员测试
    del dict1["temperature"]  # 删除
equalbyvalue = dict2 == dict3
itemcount2 = len(dict2)       # 长度,即大小,即项数
isempty2 = len(dict2) == 0    # 是否为空测试
for key in dict2:             # 通过键进行迭代
    print(key, dict2[key])    # 打印键和值
    dict2[key] += 10          # 修改访问的键值对
for key in sorted(dict2):     # 按键的排序顺序进行迭代
    print(key, dict2[key])    # 打印键和值
for value in dict2.values():  # 通过值进行迭代
    print(value)
for key, value in dict2.items():  # 通过键值对进行迭代
    print(key, value)

dict5 = {}  # {x: dict2[x] + 1 for x in dict2}  # 字典推导式 (Python 2.7 及以后版本)
dict6 = dict2.copy()  # 浅拷贝
dict6.update({"i": 60, "j": 30})  # 添加或覆盖,就像列表的 extend
dict7 = dict2.copy()
dict7.clear()  # 清空
sixty = dict6.pop("i")  # 移除键 i,返回其值
print(dict1, dict2, dict3, dict4, dict5, dict6, dict7, equalbyvalue, itemcount2, sixty)

字典的语法

字典可以直接创建或通过序列转换。字典用花括号 {} 括起来。

d = {'city': 'Paris', 'age': 38, (102, 1650, 1601): 'A matrix coordinate'}
seq = [('city', 'Paris'), ('age', 38), ((102, 1650, 1601), 'A matrix coordinate')]
print(d)
# {'city': 'Paris', 'age': 38, (102, 1650, 1601): 'A matrix coordinate'}

print(dict(seq))
# {'city': 'Paris', 'age': 38, (102, 1650, 1601): 'A matrix coordinate'}

print(d == dict(seq))
# True

字典也可以通过 zip 函数轻松创建:

seq1 = ('a', 'b', 'c', 'd')
seq2 = [1, 2, 3, 4]
d = dict(zip(seq1, seq2))
print(d)
# {'a': 1, 'b': 2, 'c': 3, 'd': 4}

字典操作

字典的操作有些独特。由于字典项是无序的,无法进行切片操作。

d = {'a': 1, 'b': 2, 'cat': 'Fluffers'}
print(d.keys())   # ['a', 'b', 'cat']
print(d.values()) # [1, 2, 'Fluffers']
print(d['a'])     # 1

d['cat'] = 'Mr. Whiskers'  # 修改值
print(d['cat'])  # 'Mr. Whiskers'

print('cat' in d)  # True
print('dog' in d)  # False

合并字典

通过使用 update 方法可以合并两个字典。如果存在重复的键,update 方法会覆盖原来的值。

d = {'apples': 1, 'oranges': 3, 'pears': 2}
ud = {'pears': 4, 'grapes': 5, 'lemons': 6}
d.update(ud)
print(d)
# {'apples': 1, 'oranges': 3, 'pears': 4, 'grapes': 5, 'lemons': 6}

从字典中删除

使用 del 删除字典中的某个成员:

del d['apples']
print(d)
# {'oranges': 3, 'pears': 4, 'grapes': 5, 'lemons': 6}

练习

编写一个程序:

  1. 提示用户输入一个字符串,然后创建以下字典。字典的值是字符串中的字母,对应的键是字符串中的位置。
  2. 将键为整数 3 的条目替换为值 "Pie"。
  3. 提示用户输入一个由数字组成的字符串,然后打印出与这些数字对应的值。
最后修改: 2025年01月30日 星期四 23:39