专业编程基础技术教程

网站首页 > 基础教程 正文

失业程序员复习python笔记---字典和集合(1)

ccvgpt 2025-05-02 09:22:49 基础教程 14 ℃

字典是一系列由键和值配对组成的集合


失业程序员复习python笔记---字典和集合(1)

相比于列表和元组,字典的性能更优,特别是对于查找、添加和删除操作,字典都能在常数时间复杂度内完成。


集合和字典基本相同,唯一的区别,就是集合没有键和值的配对,是一系列无序的、唯一的元素组合。


字典的创建和访问方式如下:

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

Tags:

最近发表
标签列表