字典基础概念
Python字典(Dictionary)是无序的键值对集合,使用{}定义,通过key: value形式存储数据。其核心特性包括:
- 键唯一性:每个键(key)必须唯一,重复键会覆盖旧值
- 动态可变性:支持增删改操作
- 高效查找:通过哈希表实现O(1)时间复杂度的键查找
- 类型灵活性:支持存储任意类型数据(字符串、列表、字典嵌套等)
案例解析
# 案例2-6字典操作修正版
#1 创建空字典并添加元素
print('\n#1')
zdict = {} # 修正错误的{{}}
zdict['w1'] = 'hello'
zdict['w2'] = 'ziwang.com'
print('zdict', zdict) # 输出:{'w1': 'hello', 'w2': 'ziwang.com'}
#2 直接初始化字典
print('\n#2')
zdict = {
'url1': 'TopQuant.vip',
'url2': 'www.TopQuant.vip',
'url3': 'ziwang.com'
}
print('zdict', zdict)
#3 字典操作演示
print('\n#3')
zdict = {}
vdict = {
'url1': 'TopQuant.vip',
'url2': 'www.TopQuant.vip',
'url3': 'ziwang.com'
}
zdict['w1'] = 'ziwang.com'
s2 = zdict['w1']
print('s2', s2) # 输出:ziwang.com
s3 = vdict['url2']
print('s3', s3) # 输出:www.TopQuant.vip
字典内置函数与方法(Python3更新版)
类别 | 方法/函数 | 说明 |
---|---|---|
基础操作 | len(dict) | 返回键值对数量 |
dict.keys() | 返回所有键的视图 | |
dict.values() | 返回所有值的视图 | |
数据操作 | dict.items() | 返回键值对元组的视图 |
dict.get(key, default) | 安全获取值,key不存在时返回default | |
dict.setdefault(key) | 获取值,若不存在则插入默认值 | |
dict.update(other_dict) | 合并字典 | |
结构操作 | dict.clear() | 清空字典 |
dict.copy() | 浅拷贝字典 | |
dict.fromkeys(seq) | 从序列创建新字典 |
注意:Python3已移除has_key()方法,建议使用in运算符替代(如if key in dict)
实战技巧
字典推导式
# 生成平方数字典
squares = {x: x**2 for x in range(1,6)} # {1:1, 2:4, ...,5:25}
嵌套字典
user_info = {
"name": "张三",
"skills": ["Python", "SQL", "Pandas"],
"address": {
"city": "北京",
"zipcode": "100000"
}
}
字典排序
# 按值排序
sorted_dict = dict(sorted(original_dict.items(), key=lambda x: x[[1]()][[1]()] = freq.get(word, 0) + 1
配置管理:替代多个全局变量
config = {
"db_host": "localhost",
"db_port": 3306,
"timeout": 30
}
缓存机制:实现LRU缓存
cache = {}
def get_data(key):
if key in cache:
return cache[key] # 命中缓存
data = fetch_from_db(key)
cache[key] = data # 缓存新数据
return data
进阶提示:对于需要保持插入顺序的场景,建议使用Python3.7+的
collections.OrderedDict
通过本文的系统解析,读者可以掌握字典的核心操作方法,并在实际开发中灵活运用。后续将推出《字典性能优化实战》系列,欢迎关注获取更多Python开发技巧!