字典元素的添加
增加一个元素
#增加一个元素
如果key值存在 则更新对应的value
如果key不存在 则添加对应的value
service = {
'http':80,
'ftp':23,
'ssh':22
}
service['https'] = 443
print(service)
service['ftp'] = 21
print(service)
结果
增加一组 k | v 值
service = {
'http':80,
'ftp':23,
'ssh':22
}
service_backup = {
'tomcat':8080,
'mysql':3306
}
service.update(service_backup)
print(service)
service.update(dns=53)
print(service)
结果
key是否存在进行添加
service = {
'http':80,
'ftp':23,
'ssh':22
}
# 如果key值存在 则不做修改
# 如果key值不存在 则添加对应的值
service.setdefault('http',9090)
print(service)
service.setdefault('oracle',44575)
print(service)
结果
字典元素的删除
类别一
service = {
'http':80,
'ftp':23,
'ssh':22
}
## pop删除指定的key对应的value值
item = service.pop('http')
print(item)
print(service)
结果
删除最后一个k-v (k,v)
service = {
'http':80,
'ftp':23,
'ssh':22
}
# 删除最后一个k-v (k,v)
a = service.popitem()
print(a)
print(service)
结果
清空字典内容
service = {
'http':80,
'ftp':23,
'ssh':22
}
# 清空字典内容
service.clear()
print(service)
结果
字典元素的查看
查看字典中所有的key值
service = {
'http':80,
'ftp':23,
'ssh':22
}
# 查看字典中所有的key值
print(service.keys())
结果
查看字典中所有的value值
service = {
'http':80,
'ftp':23,
'ssh':22
}
# 查看字典中所有的value值
print(service.values())
结果
查看字典中的k-v
service = {
'http':80,
'ftp':23,
'ssh':22
}
# 查看字典中的k-v
print(service.items())
结果
查看字典中新加端口的value值
service = {
'http':80,
'ftp':23,
'ssh':22
}
# print(service['https'])
print(service.get('https'))
print(service.get('https',443))
结果