字典的创建
字典
key-value 键值对存储的一种数据结构
value值可以是任意数据类型:int float long list tuple set dict
定义一个空字典
In [1]: d = {}
In [2]: type(d)
Out[2]: dict
创建字典
d = {
'数学': [88, '王老师', '十年'],
'语文': [78, '李老师', '五年']
}
print(d)
print(d['数学'])
d2 = {
'a':1,
'b':2
}
print(d2)
d3 = {
'a':{1,2,3},
'b':{2,3,4}
}
print(d3)
字典的嵌套
students = {
'03146024':{
'name':'安某',
'age':18,
'score':90
},
'03146025':{
'name':'张某',
'age':19,
'score':80
}
}
print(students['03146024']['name'])
工厂函数
d5 = dict(a=1,b=2)
print(d5)
字典的特性
d = {
'1':'a',
'8':'b',
'2':'a'
}
字典不支持索引
print(d[0]) #出现报错
print(d['1']) #出现报错
字典不支持切片
print(d[::-1]) #出现报错
字典的重复和连接是无意义的,字典的key是唯一的
成员操作符:判断的是某个值是否为字典的key
print('1' in d)
print('1' not in d)
字典的for循环:默认遍历字典的key值
for key in d:
print(key)
遍历字典
for key in d:
print(key,d[key])
字典的增加
services = {
'http': 80,
'ftp': 21,
'ssh': 22
}
1.增加一个元素
1).如果key值存在,则更新对应的value值
2).如果key值不存在,则添加对应的key-value值
services['mysql'] = 3306
print(services)
services['http'] = 443
print(services)
2.添加多个key-value值
1).如果key值存在,则更新对应的value值
2).如果key值不存在,则添加对应的key-value值
service_backup = {
'tomcat':8080,
'https':443,
'http':8888
}
services.update(service_backup)
print(services)
services.update(flask=9000,http=999)
print(services)
3.setdefault添加key值:
1).如果key值存在,则不做修改
2).如果key值不存在,则添加对应的key-value值
services.setdefault('http',9000)
print(services)
services.setdefault('oracle',44575)
print(services)
字典的删除
services = {
'http': 80,
'ftp': 21,
'ssh': 22,
'mysql':3306
}
1.del关键字
del services['http']
print(services)
2.pop删除指定的key的key-value值
1.)如果key存在,删除,并且返回删除key对应的value值
2.)如果key不存在,直接报错
item = services.pop('http')
print(item)
print(services)
3.popitem删除最后一个key-value
item = services.popitem()
print('删除的key-value对应的是:',item)
print(services)
4.清空字典内容
services.clear()
print(services)
字典的查看
查看字典里面的key值
print(service.keys())
查看字典里面的所有value值
print(service.values())
遍历字典
for k,v in service.items():
print(k,'---->',v)
for k in service:
print(k,'---->',service[k])
查看指定key对应的value值
key值不存在,程序会报错
print(service['http'])
print(service['https']) #出现报错
get方法获取指定key对应的value值
如果key值存在,返回对应的value值
如果key值不存在,默认返回None,如果需要指定返回的值,传值即可
print(service.get('https'))
print(service.get('http'))