一、字典的定义
字典是一个无序的数据集合,通常输出的顺序和定义的顺序不一致
1. 字典的创建
users = ['user1','user2']
passwd = ['123','456']
print(zip(users,passwd))
print(list(zip(users,passwd)))
print(dict(zip(users,passwd)))
2.空字典的定义
s = {} #空字典
print(type(s))
d = dict() #空字典
print(d,type(d))
3. 字典格式:key-value键值对
字典的key值是唯一的
s = {
'westos':[190,521,231],
'mysql':[100,99,88]
}
print(s,type(s))
4. 工厂函数
d1 = dict(a=1,b=2)
print(d1,type(d1))
5.嵌套
students = {
'03113009':{
'name':'laoli',
'age':39,
'score':59
},
'03113010':{
'name':'westos',
'age':18,
'score':61
}
}
print(students['03113009']['name'])
print(students['03113010'])
6.分批赋相同的value值
print({}.fromkeys({'1','2'},'000000'))
二、字典的特性
字典不支持索引和切片,字典的重复和连接也是无意义的。
1. 成员操作符
d = {
'1':'a',
'2':'b'
}
print('1' in d) #对key进行判定
print('1' not in d)
2. for循环(遍历字典的key值)
d = {
'1':'a',
'2':'b'
}
for key in d:
print(key)
遍历字典
d = {
'1':'a',
'2':'b'
}
for key in d: #与下一个作用类似
print(key,d[key])
for k,v in d.items():
print(k,v)
三、字典的增加
1. 添加不存在的项
services = {
'http':80,
'mysql':3306,
'smtp':25
}
print(services)
services['ftp'] = 21
print(services)
2. 添加已经存在的项,会更改值
services = {
'http':80,
'mysql':3306,
'smtp':25
}
print(services)
services['http'] = 443
print(services)
3. 添加多个key-value值
如果添加的key-value存在,则只改变键值;不存在的项会直接添加
services = {
'http':80,
'mysql':3306,
'smtp':25
}
services_backup = {
'https':443,
'tomcat':8080,
'http':8080
}
print(services)
services.update(services_backup)
print(services)
services.update(flask=9000,http=8000)
print(services)
4. setdefault添加key值
如果key值存在,不做修改;如果key值不存在,添加对应的key-value
services = {
'http':80,
'mysql':3306,
'smtp':25
}
print(services)
services.setdefault('http',9090)
print(services)
services.setdefault('oracle',44575)
print(services)
四、字典的删除
1. del删除指定的key-value键值对
services = {
'http':80,
'mysql':3306,
'smtp':25
}
print(services)
del services['http']
print(services)
2. pop删除指定的key的key-value
如果key存在,删除,并返回删除key对应的value;如果key不存在,报错
services = {
'http':80,
'mysql':3306,
'smtp':25
}
item = services.pop('http')
print(item)
print(services)
3. popitem删除最后一个key-value值对
services = {
'http':80,
'mysql':3306,
'smtp':25
}
print(services)
item = services.popitem()
print(services)
4. clear清空字典
services = {
'http':80,
'mysql':3306,
'smtp':25
}
services.clear()
print(services)
五、字典的查看
1. 查看字典的key值
services = {
'http':80,
'mysql':3306,
'smtp':25
}
print(services.keys())
2. 查看字典的value值
services = {
'http':80,
'mysql':3306,
'smtp':25
}
print(services.values())
3. 查看字典的key-value值
services = {
'http':80,
'mysql':3306,
'smtp':25
}
print(services.items())
4. 查看key的value值
key不存在,默认返回None;key不存在,有defaulte,则返回defaulte值
services = {
'http':80,
'mysql':3306,
'smtp':25
}
print(services.get('https'))
print(services.get('http'))
5. for迭代
services = {
'http':80,
'mysql':3306,
'smtp':25
}
for k in services:
print(k,services[k])
6. get方法
如果key值存在,返回;如果不存在,默认返回None,如果需要指定返回值,传值即可
services = {
'http':80,
'mysql':3306,
'smtp':25
}
print(services.get('https','key not exist'))
print(services.get('mysql','key not exist'))