1.定义一个字典
s = {}
print(s,type(s))

2.字典特性
(1)字典:k v 键值对的形式存在的
s = {
'linux':[100,99,89],
'python':[90,99,100]
}
print(s,type(s))

(2)工厂函数
d = dict()
print(d,type(d))
d = dict(a=1,b=2)
print(d,type(d))

(3)字典的嵌套
student = {
123:{
'name':'tom',
'age':18,
'score':99
},
456:{
'name':'lily',
'age':18,
'score':89
}
}
print(student)
print(student[123]['score'])

(4)字典不支持切片
d = {
'1':'a',
'2':'b'
}
print(d[1])

(5)成员操作符 针对的是key
d = {
'1':'a',
'2':'b'
}
print('1' in d)
print('a' in d)

(6)for循环 针对的是key
d = {
'1':'a',
'2':'b'
}
for key in d:
print(key)

(7)遍历字典
d = {
'1':'a',
'2':'b'
}
for key in d:
print(key,d[key])

3.字典元素的添加
(1)增加一个元素,如果key值存在 则更新对应的value,如果key不存在 则添加对应的value
service = {
'http':80,
'ftp':23,
'ssh':22
}
service['https'] = 443
print(service)
service['ftp'] = 21
print(service)

(2)查看某个key是否存在
service = {
'http':80,
'ftp':23,
'ssh':22
}
print(service.get('nfs'))

(3)如果key值存在 则不做修改, 如果key值不存在 则添加对应的值
service = {
'http':80,
'ftp':23,
'ssh':22
}
service.setdefault('http',9090)
print(service)
service.setdefault('oracle',44575)
print(service)

4.字典元素的删除
(1)pop删除指定的key对应的value值
service = {
'http':80,
'ftp':23,
'ssh':22
}
item = service.pop('http')
print(item)
print(service)

(2)删除最后一个k-v (k,v)
service = {
'http':80,
'ftp':23,
'ssh':22
}
a = service.popitem()
print(a)
print(service)

(3) 清空字典内容
service = {
'http':80,
'ftp':23,
'ssh':22
}
service.clear()
print(service)

5.字典元素的查看
(1)查看字典中所有的key值
service = {
'http':80,
'ftp':23,
'ssh':22
}
print(service.keys())

(2) 查看字典中所有的value值
service = {
'http':80,
'ftp':23,
'ssh':22
}
print(service.values())

(3)查看字典中的k-v
service = {
'http':80,
'ftp':23,
'ssh':22
}
print(service.items())

(4)查看是否有key
没有会报错
service = {
'http':80,
'ftp':23,
'ssh':22
}
print(service['https'])

service = {
'http':80,
'ftp':23,
'ssh':22
}
print(service.get('https'))

来源:CSDN
作者:weixin_43384009
链接:https://blog.csdn.net/weixin_43384009/article/details/103570291