python中的資料型別——字典(dict)
阿新 • • 發佈:2018-12-05
字典的建立
字典
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'))