字典
无序的数据集合
通常输出数序和定义顺序没有关系
定义
Service = ['http', 'ssh', 'mysql']
Port = [80, 22, 3306]
print(zip(Service, Port))
print(list(zip(Service, Port)))
print(dict(zip(Service, Port)))
s = {}
print(type(s))
Service = {
'http':80,
'mysql':3306,
'ssh':22,
'ftp':21,
'telnet':23,
'https':443
}
d = dict(a=1, b=2)
print(d)
嵌套
Service = {
'http':{
'port':22,
'status':'active'
},
'mysql':{
'port':3306,
'status':'inactive'
}
}
print(Service['mysql']['port'])
所有的key的value值相同
print({}.fromkeys({'1' ,'2'}, '0000'))
字典的特性
Service = {
'http':80,
'mysql':3306,
'ssh':22,
'ftp':21,
'telnet':23,
'https':443
}
成员操作符 key
print('http' in Service)
print('80' in Service)
支持循环,key为循环参数
for n in Service:
print(n, Service[n])
for k,v in Service.items():
print(k, v)
定义
Service = {
'http':80,
'mysql':3306,
'ssh':22,
'ftp':21,
'telnet':23,
'https':443,
'smtp':25
}
添加/修改
Service['oracle'] = 1521
添加多个
Service_Add = {
'tomcat':8080,
'flask':9000
}
Service.update(Service_Add)
print(Service)
Service.update(flask=9000, http=8080)
print(Service)
setdefault添加key值
key存在不做修改
key不存在,添加默认值
Service.setdefault('http', 8080)
Service.setdefault('oracle',1531)
删除
del Service['http']
pop 返回value值,否则报错
Service.pop('https')
popitem 删除最后一个键值对
Service.popitem()
字典清空
Service.clear()
查看key
Service.keys()
查看值
Service.values()
查看键值对
Service.items()
查看key的value值
key存在,返回值
key不存在,返回None
如果Key不存在,有default,返回默认值
Service.get('http', 'key not exist')