01.字典的特性
d = {
'1':'a',
'2':'b'
}
字典不支持索引
print(d['1'])
字典不支持切片
# print(d[:])
字典的重复和连接无意义,因为字典的key值是唯一的
成员操作符
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])
for key,value in d.items():
print(key,value)
02.字典的增加
service = {
'http':80,
'ftp':21,
'ssh':22
}
#增加一个元素
#如果key值存在,则更新对应的value值
#如果key值不存在,则添加对应的key-value值
service['mysql'] = 3306
print(service)
service['http'] = 443
print(service)
#添加多个key-value值
service_backup = {
'https':443,
'tomcat':8080,
'http':8080
}
service.update(service_backup)
print(service)
service.update(flask=9000,http=8000)
print(service)
#setdefault添加key值
#如果key值存在,不做修改
#如果key值不存在,则添加对应的key-value
service.setdefault('http',9090)
print(service)
service.setdefault('oracle',44575)
print(service)
03.字典的删除
services = {
'http':80,
'ftp':21,
'ssh':22
}
del services['http']
print(services)
#pop删除指定key的key-value
#如果key存在,删除,并返回删除key对应的value
#如果不存在,报错
item = services.pop('http')
print(item)
print(services)
#popitem删除最后一个key-value值
item = services.popitem()
print('删除的是:',item)
print(services)
#清空字典内容
services.clear()
print(services)
04.字典的查看
services = {
'http':80,
'ftp':21,
'ssh':22
}
#查看字典的key值
print(services.keys())
#查看字典的value值
print(services.values())
#查看字典的key-value值
print(services.items())
#查看key的value值
#key不存在,默认返回none
#key不存在,有default值,则返回default值
print(services.get('http'))
#遍历
for k,v in services.items():
print(k,'--->',v)
for k in services:
print(k,'--->',services[k])