字典的常见操作<一>

<1>修改元素

字典的每个元素中的数据是可以修改的,只要通过key找到,即可修改

Demo

1
2
3
4
5
from pip._vendor.distlib.compat import raw_input
info = {'name':'班长', 'id':100, 'sex':'f', 'address':'地球亚洲中国北京'}
newId = raw_input('请输入新的学号')
info['id'] = int(newId)
print('修改之后的id为%d:'%info['id'])

 运行结果:

请输入新的学号123
修改之后的id为123:

<2>添加元素

demo:访问不存在的元素

1
2
info = {'name':'班长', 'sex':'f', 'address':'地球亚洲中国北京'}
print('id为:%d'%info['id'])

 运行结果:KeyError: 'id'

如果在使用 变量名['键'] = 数据 时,这个“键”在字典中,不存在,那么就会新增这个元素

demo:添加新的元素

1
2
3
4
5
6
from pip._vendor.distlib.compat import raw_input
info = {'name':'班长', 'sex':'f', 'address':'地球亚洲中国北京'}
# print('id为:%d'%info['id'])#程序会终端运行,因为访问了不存在的键
newId = raw_input('请输入新的学号')
info['id'] = newId
print('添加之后的id为:%s'%info['id'])y

 运行结果:

请输入新的学号123
添加之后的id为:123

<3>删除元素

对字典进行删除操作,有一下几种:

  • del
  • clear()

demo:del删除指定的元素

1
2
3
4
info = {'name':'班长', 'sex':'f', 'address':'地球亚洲中国北京'}
print('删除前,%s'%info['name'])
del info['name']
print('删除后,%s'%info['name'])

 运行结果:

删除前,班长
Traceback (most recent call last):
  File "D:\Python_Workspace\HelloWorld\aa\Hello.py", line 7, in <module>
    print('删除后,%s'%info['name'])
KeyError: 'name'


demo:del删除整个字典

1
2
3
4
info = {'name':'monitor', 'sex':'f', 'address':'China'}
print '删除前,',info
del info
print '删除后,',info

 运行结果:

Traceback (most recent call last):
  File "D:\Python_Workspace\HelloWorld\aa\Hello.py", line 4, in <module>
删除前, {'address': 'China', 'name': 'monitor', 'sex': 'f'}
    print ('删除后,',info)
NameError: name 'info' is not defined

 

posted on   LoaderMan  阅读(183)  评论(0编辑  收藏  举报

编辑推荐:
· ASP.NET Core 模型验证消息的本地化新姿势
· 对象命名为何需要避免'-er'和'-or'后缀
· SQL Server如何跟踪自动统计信息更新?
· AI与.NET技术实操系列:使用Catalyst进行自然语言处理
· 分享一个我遇到过的“量子力学”级别的BUG。
阅读排行:
· 为什么AI教师难以实现
· 如何让低于1B参数的小型语言模型实现 100% 的准确率
· AI Agent爆火后,MCP协议为什么如此重要!
· 【译】Visual Studio(v17.13)中新的调试和分析特性
· Draw.io:你可能不知道的「白嫖级」图表绘制神器
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

喜欢请打赏

扫描二维码打赏

了解更多

点击右上角即可分享
微信分享提示