网站首页 > 基础教程 正文
在 Python 中,字典(dict) 是一种内置的数据结构,用于存储键值对。
字典中的键必须是唯一的,且不可变(例如,字符串、数字或元组),而值可以是任意类型的对象。
示例如下:
my_dict = {}
my_dict['张三'] = {'性别': '男', '年龄': 19}
my_dict[1] = 'one'
# 输出:
# {'张三': {'性别': '男', '年龄': 19}, 1: 'one'}
print(my_dict)
# 删除键值对
del my_dict['张三']
# 输出: {1: 'one'}
print(my_dict)
# 访问键值对
# 输出: key: 1, value: one
for key, value in my_dict.items():
print(f'key: {key}, value: {value}')
除了内置的字典, Python 标准库 collections 模块中还提供了几种特殊字典类型 defaultdict、OrderedDict、ChainMap 和 Counter,它们各自有不同的用途和特性。
defaultdict
defaultdict 是 dict 的一个子类,可以为字典中的键提供一个默认值,访问不存在键的时候不会抛出异常。
示例如下:
from collections import defaultdict
# int类型的默认值为0
my_dict = defaultdict(int)
my_dict['a'] += 1
my_dict['b'] = my_dict['a'] + 1
my_dict['c'] = my_dict['b'] + 1
# 输出: defaultdict(<class 'int'>, {'a': 1, 'b': 2, 'c': 3})
print(my_dict)
# 输出: 0
print(my_dict['d'])
OrderedDict
OrderedDict 是 dict 的子类,根据键值对的插入顺序进行存储。
在 Python 3.7 及更高版本中,普通的 dict 默认支持上述功能。
示例如下:
from collections import OrderedDict
my_dict = OrderedDict()
my_dict[3] = 'three'
my_dict[2] = 'two'
my_dict[1] = 'one'
# 输出:
# OrderedDict([(3, 'three'), (2, 'two'), (1, 'one')])
print(my_dict)
ChainMap
ChainMap 是一个类,用于将多个字典组合在一起,在 ChainMap 对象查找一个键时,会按照顺序在所有字典中查找,直到找到该键。
from collections import ChainMap
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 20, 'c': 30}
chain_map = ChainMap(dict1, dict2)
# 输出: 1 (来自dict1)
print(chain_map['a'])
# 输出: 2 (来自dict1, 因为dict1中的'b'在dict2中的'b'前面)
print(chain_map['b'])
# 输出: 30 (来自dict2)
print(chain_map['c'])
Counter
Counter 是 dict 的子类,用于统计元素出现的次数。
示例如下:
from collections import Counter
my_list = [1, 1, 2, 2, 2, 3]
my_counter = Counter(my_list)
# 输出: 2 (1出现的次数为2)
print(my_counter[1])
# 输出: 3 (2出现的次数为3)
print(my_counter[2])
# 输出: 1 (3出现的次数为1)
print(my_counter[3])
my_str = 'hello world'
my_counter = Counter(my_str)
# 输出: 2 ('o'出现的次数为2)
print(my_counter['o'])
猜你喜欢
- 2025-05-02 Python代码使用字典推导式(python的字典怎么用)
- 2025-05-02 失业程序员复习python笔记——字典和集合(2)
- 2025-05-02 Python中删除字典元素的方法(python 字典 删除)
- 2025-05-02 探索 Python 中字典推导式的艺术性
- 2025-05-02 如何在Python中按值对字典进行排序?
- 2025-05-02 Python哈希表:了解哈希函数与字典
- 2025-05-02 失业程序员复习python笔记---字典和集合(1)
- 2025-05-02 Python 字典合并、求和大作战,轻松搞定各路数据
- 2025-05-02 Python 访问字典视图 #python爬虫
- 2025-05-02 python学习——025python遍历字典四种方法
- 06-18单例模式谁都会,破坏单例模式听说过吗?
- 06-18Objective-c单例模式的正确写法「藏」
- 06-18单例模式介绍(单例模式都有哪些)
- 06-18前端设计-单例模式在实战中的应用技巧
- 06-18PHP之单例模式(php单例模式连接数据库)
- 06-18设计模式:单例模式及C及C++实现示例
- 06-18python的单例模式(单例 python)
- 06-18你认为最简单的单例模式,东西还挺多
- 最近发表
- 标签列表
-
- jsp (69)
- gitpush (78)
- gitreset (66)
- python字典 (67)
- dockercp (63)
- gitclone命令 (63)
- dockersave (62)
- linux命令大全 (65)
- pythonif (86)
- location.href (69)
- dockerexec (65)
- tail-f (79)
- queryselectorall (63)
- location.search (79)
- bootstrap教程 (74)
- 单例 (62)
- linuxgzip (68)
- 字符串连接 (73)
- html标签 (69)
- c++初始化列表 (64)
- mysqlinnodbmyisam区别 (63)
- arraylistadd (66)
- mysqldatesub函数 (63)
- window10java环境变量设置 (66)
- c++虚函数和纯虚函数的区别 (66)