字典
1.定义一个字典
s = {}
print(s,type(s))
2.字典 key-value 键值对
s = {
'linux':[100,99,80],
'python':[89,90,100]
}
print(s,type(s))
3.工厂函数
d = dict()
print(d,type(d))
d = dict(a=1,b=2)
print(d,type(d))
4.字典的嵌套
student = {
123:{
"name":'tom',
'age':18,
'score':99
},
456:{
'name':'lily',
'age':19,
'score':98
}
}
print(student[123]['score'])
5.字典的特性
d = {
'1':'a',
'2':'b'
}
print(d['1'])
# 字典不支持切片
# 成员操作符
print('1' in d)
print('1' not in d)
# for循环 针对key
for key in d:
print(key)
# 遍历字典
for key in d:
print(key,d[key])
6.字典元素的增加
service = {
'http':80,
'ftp':23,
'ssh':22
}
# 增加一个元素
# 如果key值存在,则更新对应的value值
# 如果key值不存在,则添加对应的值
service['https'] = 443
print(service)
service['ftp'] = 21
print(service)
service_backup ={
'tomcat':8080,
'mysql':3306
}
service.update(service_backup)
print(service)
service.update(dns=53)
print(service)
# 如果key值存在,不做修改
# 如果key值不存在,则添加对应的值
service.setdefault('http',9090)
print(service)
service.setdefault('oracle',44575)
print(service)
7.字典元素的删除
service = {
'http':80,
'ftp':23,
'ssh':22,
}
# pop删除指定key对应的value值
a = service.popitem()
print(a)
print(service)
# 清空字典内容
service.clear()
print(service)
8.字典元素的查看
service = {
'http':80,
'ftp':23,
'ssh':22,
}
# 查看字典中所有的key值
print(service.keys())
# 查看字典中所有的value值
print(service.values())
# 查看字典中的key-value
print(service.items())
print(service.get('https',443))
# print(service['https'])