3字典是一个无序的数据集合,使用print输出字典时
#通常输出的顺序和定义的顺序不一致
users = ['user1','user2']
passwd = ['123','456']
print(zip(users,passwd))
print(list(zip(users,passwd)))
print(dict(zip(users,passwd)))
# s = {}
# print(type(s))
#字典:key-value 键值对
#value值可以是任意数据类型
# s = {
# 'linux':[100,99,88],
# 'westos':[190,564,645]
# }
#
# print(s)
# print(type(s))
#工厂函数
# d = dict()
# print(d)
# print(type(d))
#
# d1 = dict(a=1,b=2)
# print(d1)
# print(type(d1))
#字典的嵌套
students = {
'03113009':{
'name':'tom',
'age':18,
'score':80
},
'03113010':{
'name': 'laoli',
'age': 19,
'score':30
}
}
print(students['03113010']['name'])
结果:
laoli
#所有的key和value值是一样的情况
print({}.fromkeys({'1','2'},'03113009'))
结果:
{'2':'03113009','1':'03113090'}
d = {
'1':'a',
'2':'b'
}
#字典不支持索引
# print(d['1'])
结果:
error
#字典不支持切片
# print(d[:])
结果:
error
#字典的重复和连接无意义,因为字典的key值是唯一的
#成员操作符
print('1' in d)
print('1' not in d)
结果:
Ture
False
#for循环,默认遍历字典的key值
for key in d:
print(key)
结果:
1 2
#遍历字典
for key in d:
print(key,d[key])
结果:
1 a
2 b
for key,value in d.items():
print(key,value)
结果:
1 a
2 b
service = {
'http':80,
'ftp':21,
'ssh':22
}
#增加一个元素
#如果key值存在,则更新对应的value值
#如果key值不存在,则添加对应的key-value值
service['mysql'] = 3306
print(service)
service['http'] = 443 //会修改以前的value值
print(service)
#添加多个key-value值
service_backup = {
'https':443,
'tomcat':8080,
'http':8080
}
service.update(service_backup)
print(service)
service.update(flask=9000,http=8000) //http的value值变为8000
print(service)
#setdefault添加key值
#如果key值存在,不做修改
#如果key值不存在,则添加对应的key-value
service.setdefault('http',9090) //因为http已经存在,所有它的value值不做修改
print(service)
service.setdefault('oracle',44575) //添加oracle 44575
print(service)
service = {
'http':80,
'ftp':21,
'ssh':22
}
# del service['http']
# print(service)
结果:
{'ftp':21,'ssh':22}
#pop删除指定key的key-value
#如果key存在,删除,并且返回删除key对应的value
#如果key不存在,报错
# item = service.pop('http')
# print(item)
结果:
80
# print(service)
结果:
{'ftp':21,'ssh':22}
#popitem删除最后一个key-value值
item = service.popitem()
print('删除的key-value对是:',item)
print(service)
结果:
删除的key-value对是:('ssh',22)
{'http':80,'ftp':21}
#清空字典内容
service.clear()
print(service)
结果:
{}
service = {
'http':80,
'ftp':21,
'ssh':22
}
#查看字典的key值
print(service.keys())
结果:
dict_keys(['http','ftp','ssh'])
#查看字典的value值
print(service.values())
结果:
dict_values([80,21,22])
#查看key的value值;key不存在,报错
# print(service['https'])
结果:
报错
#查看key的value值
#key不存在,默认返回None
#key不存在,有default,则返回default
print(service.get('https',443))
print(service.get('https'))
结果:
443
None
#遍历
for k,v in service.items():
print(k,'--->',v)
结果:
http ---> 80
ftp ---> 21
ssh ---> 22
# print(service['https'])
if 'https' in service:
print(service['https'])
else:
print('key not exist')
结果:
Key not exits
#get方法获取指定key对应的value值
#如果key值存在,返回对应的value值
#如果key值不存在,默认返回None,如果需要指定返回值,传值即可
print(service.get('https','ket not exist'))