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