1.字典(dict)的定义
字典是一个无序的数据集合,通常输出顺序和定义顺序不一样
users = ['user1','user2']
passwds = ['123','456']
print(zip(users,passwds)) #zip压缩
print(list(zip(users,passwds))) #zip压缩为列表型
print(dict(zip(users,passwds))) #zip压缩为字典型
(1)空字典: d = {}
d = {}
print(type(d))
(2)字典中的value值可以是任意数据类型(整型,浮点型,字符串,列表等)
s = {
'westos':[100,99,88],
'redhat':[50,60,70]
} #字符串:列表
print(s,type(s))
(3)使用工厂函数定义:d = dict()
d = dict(a=1,b=2)
print(d)
print(type(d))
(4)字典的嵌套:
students = {
'03113009':{
'name':'wsp',
'age':18,
'score':90
},
'12345678':{
'name':'laoli',
'age':36,
'score':80
}
}
print(students)
print(students['12345678']['name']) #字典中是通过key值来获取value值的
字典中是通过key值来获取value值的
(5)所有key的value值一样
print({}.fromkeys({'1','2'},'000000'))
2.字典的特性
- 支持成员操作符,支持for循环
- 不支持索引、切片,并且字典的重复、连接无意义,因为字典的key值唯一
- 字典的遍历默认遍历key值
for i in d
print(i)
- 同时获取key值和value值
for k,v in d.items()
print(k,v)
3.字典的增删改查
(1)字典的增加
- 增加一个元素(若key值存在,则更新对应的value值;若key值不存在,则添加key-value值对)
services = {
'http':80,
'ftp':21,
'mysql':3306
}
services['ssh'] = 22
print(services)
services['http'] = 443
print(services)
- 增加多个元素
services = {
'http':80,
'ftp':21,
'mysql':3306
}
services_backup = {
'https':443,
'tomcat':8080,
'ssh':22
}
services.update(services_backup)
print(services) #增加多个元素,字典services中增加services_backup
services.update(flask=9000,http=8000)
print(services) #字典services中增加flask=9000,http=8000
(2)字典的修改
.setdefault()添加key值(若key值存在,不做修改;若key值不存在,则添加key-value值对)
services = {
'http':80,
'ftp':21,
'mysql':3306
}
services.setdefault('http',9090) #http存在则修改value值为9090
print(services)
services.setdefault('oracle',44575) #oracle不存在则添加'oracle':44575
print(services)
(3)字典的删除
del直接删除
services = {
'http':80,
'ftp':21,
'mysql':3306
}
del services['http']
print(services)
.pop删除指定的key的key-value(若key存在,删除并返回key对应的value值;若不存在,则报错)
services = {
'http':80,
'ftp':21,
'mysql':3306
}
item = services.pop('mysql')
print(item) #item为mysql的value值
print(services)
.popitem删除最后一个key-value值
ervices = {
'http':80,
'ftp':21,
'mysql':3306
}
item = services.popitem()
print(item)
print(services)
清空字典内容:service.clear()
services = {
'http':80,
'ftp':21,
'mysql':3306
}
services.clear()
print(services)
(4)字典的查看
- 查看字典的key值
services = {
'http':80,
'ftp':21,
'mysql':3306
}
print(services.keys())
- 查看字典的value值
services = {
'http':80,
'ftp':21,
'mysql':3306
}
print(services.values())
- 查看字典的key-value值对
services = {
'http':80,
'ftp':21,
'mysql':3306
}
print(services.items())
- 查看key的value值
services = {
'http':80,
'ftp':21,
'mysql':3306
}
print(services['http'])
.get方法获取指定key值对应的value值(如果key值存在,返回对应的value值;如果key值不存在,默认返回None,如果需要指定返回值,传值即可)
print(services.get('https','key not exist')) #https不存在,返回'key not exist'
print(services.get('firewalld')) #firewalld不存在,返回None