Python 字典基础:键值对操作、访问与核心方法大全
字典基础
每个键与值用冒号 (:) 分隔,项用逗号分隔,整体用花括号括起。无项的空字典写为两个花括号:{}。
字典键唯一,值可重复。值可为任意类型,但键必须为不可变类型:字符串、数字或元组。
访问字典值
使用方括号加键获取值。简单示例:
在线演示#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
print "dict['Name']: ", dict['Name']
print "dict['Age']: ", dict['Age']
执行结果:
dict['Name']: Zara dict['Age']: 7
尝试访问不存在的键会报错:
在线演示#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
print "dict['Alice']: ", dict['Alice']
执行结果:
dict['Alice']: Traceback (most recent call last): File "test.py", line 4, inprint "dict['Alice']: ", dict['Alice'] KeyError: 'Alice'
更新字典
可通过添加新键值对、修改现有项、删除现有项更新字典:
在线演示#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
dict['Age'] = 8 # 更新现有项
dict['School'] = "DPS School" # 添加新项
print "dict['Age']: ", dict['Age']
print "dict['School']: ", dict['School']
执行结果:
dict['Age']: 8 dict['School']: DPS School
删除字典元素
可删除单个元素、清空字典、或一次性删除整个字典。
显式删除整个字典用 del 语句:
在线演示#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
del dict['Name'] # 删除键 'Name' 的项
dict.clear() # 清空字典所有项
del dict # 删除整个字典
print "dict['Age']: ", dict['Age']
print "dict['School']: ", dict['School']
结果如下。注意 del dict 后字典不存在,抛出异常:
dict['Age']: Traceback (most recent call last): File "test.py", line 8, inprint "dict['Age']: ", dict['Age'] TypeError: 'type' object is unsubscriptable
注意:del() 方法在后续章节讨论。
字典键的特性
字典值无限制,可为任意 Python 对象(标准或用户定义)。但键有限制:
(a) 每键仅允许一项。即不允许重复键。赋值遇重复键时最后赋值生效。例如:
在线演示#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'}
print "dict['Name']: ", dict['Name']
执行结果:
dict['Name']: Manni
(b) 键必须不可变。即可用字符串、数字、元组作键,但列表等不可。例如:
在线演示#!/usr/bin/python
dict = {['Name']: 'Zara', 'Age': 7}
print "dict['Name']: ", dict['Name']
执行结果:
Traceback (most recent call last): File "test.py", line 3, indict = {['Name']: 'Zara', 'Age': 7} TypeError: unhashable type: 'list'
内置字典函数与方法
字典函数
| 序号 | 函数与说明 |
|---|---|
| 1 | cmp(dict1, dict2) - 比较两字典元素 |
| 2 | len(dict) - 返回字典总长度(等于项数) |
| 3 | str(dict) - 生成字典可打印字符串表示 |
| 4 | type(variable) - 返回传入变量类型。若为字典则返回字典类型 |
字典方法
| 序号 | 方法与说明 |
|---|---|
| 1 | dict.clear() - 移除字典 dict 所有元素 |
| 2 | dict.copy() - 返回字典 dict 浅拷贝 |
| 3 | dict.fromkeys() - 用序列 seq 创建键、值设为 value 的新字典 |
| 4 | dict.get(key, default=None) - 键 key 返回值,键不存在返回默认值 |
| 5 | dict.has_key(key) - 键在字典 dict 中返回 true,否则 false |
| 6 | dict.items() - 返回字典 dict 的 (键,值) 元组对列表 |
| 7 | dict.keys() - 返回字典 dict 的键列表 |
| 8 | dict.setdefault(key, default=None) - 类似 get(),但键不在字典时设置 dict[key]=default |
| 9 | dict.update(dict2) - 将字典 dict2 的键值对添加到 dict |
| 10 | dict.values() - 返回字典 dict 的值列表 |
Python