字典
s = {}
print(s,type(s))
字典:k v 键值对的形式存在的
s = {
'linux':[100,99,89],
'python':[90,99,100]
}
print(s,type(s))
工厂函数
d = dict()
print(d,type(d))
d = dict(a=1,b=2)
print(d,type(d))
字典的嵌套
student = {
123:{
'name':'tom',
'age':18,
'score':99
},
456:{
'name':'lily',
'age':18,
'score':89
}
}
print(student)
print(student[123]['score'])
字典的特性
d = {
'1':'a',
'2':'b'
}
print(d['1'])
字典不支持切片
成员操作符 针对的是key
print('1' in d)
print('a' in d)
for循环 针对的是key
for key in d:
print(key)
遍历字典
for key in d:
print(key,d[key])
字典元素的添加
service = {
'http':80,
'ftp':23,
'ssh':22
}
增加一个元素:如果key值存在 则更新对应的value,如果key不存在 则添加对应的value
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)
字典元素的删除
service = {
'http':80,
'ftp':23,
'ssh':22
}
pop删除指定的key对应的value值
item = service.pop('http')
print(item)
print(service)
删除最后一个k-v (k,v)
a = service.popitem()
print(a)
print(service)
清空字典内容
service.clear()
print(service)
字典元素的查看
service = {
'http':80,
'ftp':23,
'ssh':22
}
查看字典中所有的key值
print(service.keys())
查看字典中所有的value值
print(service.values())
查看字典中的k-v
print(service.items())
练习
来源:CSDN
作者:Aa. NiceMan
链接:https://blog.csdn.net/AaNiceMan/article/details/103616453