1 字典的定义
创建字典的三种方法:
(1)用空集合来创建一个字典
s = {}
print(s,type(s))
(2)字典:key-value 键值对
s = {
'linux':[98,96,94],
'python':[100,95,97]
}
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':100
}
}
print(student['123']['name'])
2 字典的特性
不支持索引、切片,字典的重复和连接无意义,因为key值唯一
d = {
'1':'a',
'2':'b'
}
print(d['1'])
(1)成员操作符:针对的是key
d = {
'1':'a',
'2':'b'
}
print('1' in d)
print('b' in d)
(2)for循环:默认针对的是key
d = {
'1':'a',
'2':'b'
}
for key in d:
print(key)
d = {
'1':'a',
'2':'b'
}
#遍历字典,打印key和value值
for key in d:
print(key,d[key])
3 字典元素的修改
(1)增加
如果key值不存在,则会增加对应的k-y
service = {
'http':80,
'ftp':23,
'ssh':22
}
service['https'] = 443
print(service)
由于key值是唯一的如果只更改value,则不会新增加,只是对原有的value值进行更新
service = {
'http':80,
'ftp':23,
'ssh':22
}
service['http'] = 8080
print(service)
增加多个key值
service = {
'http':80,
'ftp':23,
'ssh':22
}
print(service)
service_backup = {
'ftp':21,
'mysql':3306
}
print(service_backup)
service.update(service_backup)
print(service)
(2)删除
service = {
'http':80,
'ftp':23,
'ssh':22
}
del service['http']
print(service)
pop删除指定的key对应的value,如果key存在,则删除并且返回删除key对应的value(可以用变量接收),如果不存在直接报错
service = {
'http':80,
'ftp':23,
'ssh':22
}
item = service.pop('http')
print(service)
print(item)
service = {
'http':80,
'ftp':23,
'ssh':22
}
item = service.pop('https')
print(service)
print(item)
清空字典
service = {
'http':80,
'ftp':23,
'ssh':22
}
service.clear()
print(service)
(3)查看
查看字典的key’值
service = {
'http':80,
'ftp':23,
'ssh':22
}
print(service.keys())
查看字典的value值
service = {
'http':80,
'ftp':23,
'ssh':22
}
print(service.values())
查看字典的k-v
service = {
'http':80,
'ftp':23,
'ssh':22
}
print(service.items())