栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python--字典

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python--字典

字典是另一种可变容器模型,且可存储任意类型对象。

字典的每个键值 key=>value 对用冒号 : 分割,每个对之间用逗号(,)分割,整个字典包括在花括号 {} 中 ,格式如下所示:

1
d = {key1 : value1, key2 : value2, key3 : value3 }

在字典中,键是不变的,但是键值是可变的。

下面是一个简单的字典例子:

1
myinformation = {'name' = 'denggaozheng','number' = "01",'grade' = 'freshman'}

字典的一些操作
1
2
3
4
5
6
7
8
9
10
11
# 使用大括号 {} 来创建空字典
emptyDict = {}
 
# 打印字典
print(emptyDict)					#{}
 
# 查看字典的数量
print("Length:", len(emptyDict))	#0
 
# 查看类型
print(type(emptyDict))				#class = dict

使用内建函数dict来创建字典
1
2
3
4
5
6
7
8
9
10
emptyDict = dict()
 
# 打印字典
print(emptyDict)   					#{}
 
# 查看字典的数量
print("Length:",len(emptyDict))		#0
 
# 查看类型
print(type(emptyDict))				#class = dict

访问字典里面的值
1
2
3
4
5
6
7
8
#通常使用 字典名[key名]名来访问字典里的键值
di = {'name' = '1','num' = '2','class' = 3}
#现在我们访问name里的值
di['name'] #就是这么简单

#如果访问的是字典里面没有的键,那么会报错!
di = {'name' = '1','num' = '2','class' = 3}
di['number'] #error

修改字典和删除字典
1
2
3
4
5
6
7
8
9
#修改字典
di = {'name' = '1','num' = '2','class' = 3}
di['name' = '10']
print(di['name'])  #10

#删除字典
del di['name'] # 删除键 'Name'
di.clear()     # 清空字典,但是字典还是保留着的
del di         # 删除字典

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/954789.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号