网站首页 > 基础教程 正文
字典的增加,删除,更新等操作如下:
d = {'name': 'regina', 'age': 20}
d['gender'] = 'female' # 增加元素对'gender': 'female'
d['dat'] = '2025-04-11' # 增加元素对'dat': '2025-04-11'
print(d)
d['dat'] = '2025-04-10' # 更新元素对'dat': '2025-04-10'
print(d)
d.pop('dat') # 删除元素对'dat'
print(d)
D:\pyproject\venv\Scripts\python.exe D:/pyproject/py04.py
{'name': 'regina', 'age': 20, 'gender': 'female', 'dat': '2025-04-11'}
{'name': 'regina', 'age': 20, 'gender': 'female', 'dat': '2025-04-10'}
{'name': 'regina', 'age': 20, 'gender': 'female'}
Process finished with exit code 0
如果根据以上代码删除一个不存在的元素,就报如下错误
d.pop('dat1')
print(d)
D:\pyproject\venv\Scripts\python.exe D:/pyproject/py04.py
{'name': 'regina', 'age': 20, 'gender': 'female', 'dat': '2025-04-11'}
{'name': 'regina', 'age': 20, 'gender': 'female', 'dat': '2025-04-10'}
Traceback (most recent call last):
File "D:/pyproject/py04.py", line 7, in <module>
d.pop('dat1')
KeyError: 'dat1'
Process finished with exit code 1
集合增加,删除元素
s = {'regina',20}
s.add('female') # 增加元素female到集合
print(s)
s.remove('female') # 删除元素female
print(s)
D:\pyproject\venv\Scripts\python.exe D:/pyproject/py04.py
{'female', 20, 'regina'}
{20, 'regina'}
Process finished with exit code 0
字典根据键或值进行排序,代码如下
d = {'b': 1, 'a': 2, 'c': 10}
d_sorted_by_key = sorted(d.items(),key=lambda x:x[0]) # 根据字典键的升序排序
print(d_sorted_by_key)
d_sorted_by_value = sorted(d.items(),key=lambda x:x[1]) # 根据字典值的升序排序
print(d_sorted_by_value)
D:\pyproject\venv\Scripts\python.exe D:/pyproject/py04.py
[('a', 2), ('b', 1), ('c', 10)]
[('b', 1), ('a', 2), ('c', 10)]
Process finished with exit code 0
集合行排序的代码如下
s = {5,7,10,9,1,2}
print(sorted(s)) # 对集合的元素进行升序排序
print(sorted(s,reverse=True)) # 对集合的元素进行降序排序
猜你喜欢
- 2025-05-02 Python代码使用字典推导式(python的字典怎么用)
- 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遍历字典四种方法
- 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)