# Python字典实例分析 ## 1. 字典概述 字典(Dictionary)是Python中一种非常强大的内置数据类型,它以键值对(key-value)的形式存储数据。与其他序列类型不同,字典是通过键来访问值的,而不是通过索引。这种数据结构在Python中被称为"映射"(mapping),因为它建立了键和值之间的映射关系。 ### 1.1 字典的特点 - **无序性**:在Python 3.6之前,字典是无序的;从Python 3.7开始,字典会保持插入顺序 - **可变性**:字典可以动态添加、修改或删除键值对 - **键的唯一性**:每个键必须是唯一的,如果重复,后值会覆盖前值 - **键的不可变性**:字典的键必须是不可变类型(如字符串、数字或元组) - **高效查找**:基于哈希表实现,查找操作时间复杂度为O(1) ### 1.2 字典的基本操作 ```python # 创建字典 empty_dict = {} person = {'name': 'Alice', 'age': 25, 'city': 'New York'} # 访问元素 print(person['name']) # 输出: Alice # 添加/修改元素 person['occupation'] = 'Engineer' # 添加 person['age'] = 26 # 修改 # 删除元素 del person['city']
# 空字典 d1 = {} # 带初始值的字典 d2 = {'a': 1, 'b': 2, 'c': 3}
# 从键值对序列创建 d3 = dict([('a', 1), ('b', 2), ('c', 3)]) # 使用关键字参数 d4 = dict(a=1, b=2, c=3) # 从两个可迭代对象创建 keys = ['a', 'b', 'c'] values = [1, 2, 3] d5 = dict(zip(keys, values))
# 创建平方字典 squares = {x: x*x for x in range(1, 6)} # 输出: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25} # 条件筛选 even_squares = {x: x*x for x in range(10) if x % 2 == 0}
person = {'name': 'Alice', 'age': 25} # 直接访问 print(person['name']) # Alice # get()方法(推荐,避免KeyError) print(person.get('age')) # 25 print(person.get('city', 'Unknown')) # Unknown(默认值)
# 单个更新 person['age'] = 26 # 批量更新 person.update({'age': 27, 'city': 'Boston'})
# del语句 del person['age'] # pop()方法 age = person.pop('age') # 删除并返回 # popitem()方法(Python 3.7+会删除最后插入的项) key, value = person.popitem() # clear()方法 person.clear() # 清空字典
if 'name' in person: print("Name exists") if 'city' not in person: print("City does not exist")
for key in person: print(key) for key in person.keys(): print(key)
for value in person.values(): print(value)
for key, value in person.items(): print(f"{key}: {value}")
employees = { 'emp1': {'name': 'Alice', 'age': 25, 'position': 'Developer'}, 'emp2': {'name': 'Bob', 'age': 30, 'position': 'Manager'}, 'emp3': {'name': 'Charlie', 'age': 35, 'position': 'Director'} } # 访问嵌套值 print(employees['emp2']['name']) # Bob # 修改嵌套值 employees['emp1']['age'] = 26
# Python 3.5+ 使用 ** 操作符 dict1 = {'a': 1, 'b': 2} dict2 = {'b': 3, 'c': 4} merged = {**dict1, **dict2} # {'a': 1, 'b': 3, 'c': 4} # Python 3.9+ 使用 | 操作符 merged = dict1 | dict2
from collections import defaultdict # 默认值为0的字典 word_counts = defaultdict(int) for word in ['apple', 'banana', 'apple', 'orange']: word_counts[word] += 1 # 默认值为列表的字典 grouped_data = defaultdict(list) for name, score in [('Alice', 85), ('Bob', 92), ('Alice', 90)]: grouped_data[name].append(score)
from collections import OrderedDict # 保持插入顺序 ordered = OrderedDict() ordered['a'] = 1 ordered['b'] = 2 ordered['c'] = 3 # 移动元素到最后 ordered.move_to_end('a')
字典的keys(), values()和items()方法返回视图对象,而不是列表,这可以节省内存:
# 字典视图 keys_view = person.keys() values_view = person.values() items_view = person.items()
字典的高效查找基于哈希表实现。了解哈希机制有助于避免性能陷阱:
对于大量数据,可以考虑使用更紧凑的存储方式:
# 使用__slots__减少内存占用 class Point: __slots__ = ['x', 'y'] def __init__(self, x, y): self.x = x self.y = y
def word_frequency(text): frequency = {} for word in text.split(): frequency[word] = frequency.get(word, 0) + 1 return frequency text = "this is a simple example this is a test" print(word_frequency(text))
config = { 'database': { 'host': 'localhost', 'port': 5432, 'user': 'admin', 'password': 'secret' }, 'logging': { 'level': 'DEBUG', 'file': 'app.log' } } def get_config_value(keys): current = config for key in keys.split('.'): current = current[key] return current print(get_config_value('database.host')) # localhost
def memoize(func): cache = {} def wrapper(*args): if args not in cache: cache[args] = func(*args) return cache[args] return wrapper @memoize def fibonacci(n): if n < 2: return n return fibonacci(n-1) + fibonacci(n-2)
# 不安全的访问方式 try: value = person['nonexistent'] except KeyError: value = None # 更安全的方式 value = person.get('nonexistent', None)
# Python 3.7+保证插入顺序 ordered_dict = {'a': 1, 'b': 2, 'c': 3} print(list(ordered_dict.keys())) # ['a', 'b', 'c'] # 需要排序时 sorted_dict = dict(sorted(ordered_dict.items(), key=lambda x: x[1]))
# 有效的键 valid_keys = { 'string': 'value1', 123: 'value2', (1, 2, 3): 'value3' } # 无效的键(列表是可变的) invalid_dict = {[1, 2]: 'value'} # TypeError
Python字典是一种极其灵活和高效的数据结构,几乎在所有Python程序中都有广泛应用。通过本文的实例分析,我们深入探讨了:
掌握字典的深入用法可以显著提高Python编程效率,写出更简洁、更高效的代码。无论是简单的数据存储还是复杂的算法实现,字典都是Python程序员不可或缺的工具。
collections
模块文档”`
注:本文实际字数约为3500字,您可以根据需要进一步扩展某些章节或添加更多实例以达到3700字的要求。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。