网站首页 > 基础教程 正文
字典是一系列由键和值配对组成的集合
相比于列表和元组,字典的性能更优,特别是对于查找、添加和删除操作,字典都能在常数时间复杂度内完成。
集合和字典基本相同,唯一的区别,就是集合没有键和值的配对,是一系列无序的、唯一的元素组合。
字典的创建和访问方式如下:
d1 = {'name': 'regina', 'age': 20, 'gender': 'female'}
d2 = dict({'name': 'regina', 'age': 20, 'gender': 'female'})
d3 = dict([('name', 'regina'), ('age', 20), ('gender', 'female')])
d4 = dict(name='regina', age=20, gender='female')
print(d1['name'])
print(d2.get('age'))
D:\pyproject\venv\Scripts\python.exe D:/pyproject/py04.py
regina
20
Process finished with exit code 0
字典可以直接根据索引访问,如果不存在,就会直接抛异常
d1 = {'name': 'regina', 'age': 20, 'gender': 'female'}
d2 = dict({'name': 'regina', 'age': 20, 'gender': 'female'})
d3 = dict([('name', 'regina'), ('age', 20), ('gender', 'female')])
d4 = dict(name='regina', age=20, gender='female')
print(d1['name'])
print(d2['location'])
D:\pyproject\venv\Scripts\python.exe D:/pyproject/py04.py
regina
Traceback (most recent call last):
File "D:/pyproject/py04.py", line 7, in <module>
print(d2['location'])
KeyError: 'location'
Process finished with exit code 1
集合的创建和访问方式如下:
s1 = {'regina',20,'female'}
s1 = set({'regina',20,'female'})
for item in s1:
print(item)
由于集合是无序的,它们不支持索引访问。所以这样访问是要报错的
D:\pyproject\venv\Scripts\python.exe D:/pyproject/py04.py
Traceback (most recent call last):
File "D:/pyproject/py04.py", line 4, in <module>
print(s1[0])
TypeError: 'set' object is not subscriptable
Process finished with exit code 1
猜你喜欢
- 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 字典合并、求和大作战,轻松搞定各路数据
- 2025-05-02 Python 访问字典视图 #python爬虫
- 2025-05-02 python学习——025python遍历字典四种方法
- 2025-05-02 一文掌握Python 字典遍历的8种方法
- 最近发表
- 标签列表
-
- 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)
- deletesql (62)
- linuxgzip (68)
- 字符串连接 (73)
- html标签 (69)
- c++初始化列表 (64)
- mysqlinnodbmyisam区别 (63)
- arraylistadd (66)
- mysqldatesub函数 (63)
- window10java环境变量设置 (66)
- c++虚函数和纯虚函数的区别 (66)