赞
踩
字典是一个无序的数据集合,使用print输出字典的时候
通常输出的顺序和定义的顺序是不一致的
字典:key - value 键值对
value可以是任意数据类型
s = {
'linux':[100,99,88],
'westos':[190,564,645]
}
print(s,type(s))
d = dict() #定义空字典
print(type(d))
d1 = dict(a=1,b=2) #工厂函数
print(d1,type(d1))
students = {
'03113009':{
'name':'laozhao',
'age':18,
'score':80
},
'03113010':{
'name': 'laoyan',
'age': 30,
'score': 59
}
}
print(students['03113010']['age'])
print({}.fromkeys({'1','2'},'000000'))
d = {
'1':'a',
'2':'b'
}
print('2' in d)
d = {
'1':'a',
'2':'b'
}
for i in d:
print(i)
遍历字典
d = {
'1':'a',
'2':'b'
}
for i in d:
print(i,d[i])
for k,v in d.items(): #遍历key,value值
print(k,':',v)
如果key值存在,则更新对应的value值
如果key值不存在,则添加对应key-value
示例:
services = {
'http':80,
'ftp':21,
'ssh':22
}
services['mysql'] = 3306 #不存在,添加对应key-value
print(services)
services['http'] = 443 #存在,则更新对应的value值
print(services)
services = {
'http':80,
'ftp':21,
'ssh':22
}
services_backup = {
'https':443,
'tomcat':8080,
'http':8080
}
services.update(services_backup)
print(services)
services = {
'http':80,
'ftp':21,
'ssh':22
}
services.update(flask=9000,http=8000)
print(services)
如果key值存在,不做修改
如果key值不存在,添加对应的key-value
services = {
'http':80,
'ftp':21,
'ssh':22
}
services.setdefault('http',9090)
print(services)
services = {
'http':80,
'ftp':21,
'ssh':22
}
services.setdefault('oracle',44575)
print(services)
services = {
'http':80,
'ftp':21,
'ssh':22
}
del services['http']
print(services)
如果key存在,删除,并返回删除key对应的value
如果不存在,报错
示例:
services = {
'http':80,
'ftp':21,
'ssh':22
}
item = services.pop('http')
print(item)
print(services)
示例:
services = {
'http':80,
'ftp':21,
'ssh':22
}
item = services.popitem()
print('删除的是:',item)
print(services)
services = {
'http':80,
'ftp':21,
'ssh':22
}
services.clear()
print(services)
services = {
'http':80,
'ftp':21,
'ssh':22
}
print(services.keys())
services = {
'http':80,
'ftp':21,
'ssh':22
}
print(services.values())
services = {
'http':80,
'ftp':21,
'ssh':22
}
print(services.items())
key不存在,默认返回none
key不存在,有default值,则返回default值
services = {
'http':80,
'ftp':21,
'ssh':22
}
print(services.get('http'))
services = {
'http':80,
'ftp':21,
'ssh':22
}
for k,v in services.items():
print(k,'--->',v)
for k in services:
print(k,'--->',services[k])
services = {
'http':80,
'ftp':21,
'ssh':22
}
print(services.get('https','key not exist'))
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。