1.字典是另外一種可變數據類型,可存儲任意類型對象。
無序的序列,鍵值對的輸入順序和在內存中的存儲順序不一致
字典中的數據存儲以鍵值對的方式
字典的每一個鍵值(key=>value)對用冒號(:)分割,每一個對之間用逗號(,)分割,整個字典包括在花括號({})中
s = {}
print(s,type(s))
#建立一個空字典
#字典:key-value 鍵值對
s = {
'linux':[100,99,88],
'python':[190,56,78]
}
print(s,type(s)
工廠函數建立字典
d = {}
d = dict()
d = dict(a=1,b=2)
print(d,type(d))python
2.字典的嵌套
student = {
'123':{
'name':'tom',
'age':18,
'score':99
},
'456':{
'name':'lily',
'age':19,
'score':100
}
}
print(student ['123'] ['name'])mysql
3.字典元素的增長linux
service = {
'http':80,
'ftp':23,
'ssh':22
}
#增長一個元素
#若是key值存在,則更新對應的value值
#若是key值不存在,則添加對應的key-value值
service['https'] = 443
print(service)
service['ftp'] = 21
print(service)
#增長多個key值
service_backup = {
'tomcat':8080,
'mysql':3306
}
service.update(service_backup)
print(service)
service.update(flask=9000,dns=53)
print(service)
#若是key值存在:不作修改
#若是key值不存在:則添加對應的key-value
service.setdefault('http',9090)
print(service)
service.setdefault('oracle',44575)
print(service)sql
4.字典元素的刪除
dict.pop(key) :經過key刪除指定的元素,而且刪除的元素能夠被變量接收,當key存在的時候,成功刪除,當key不存在的時候,直接報錯
dict.popitem() 隨機返回並刪除字典中的一對鍵和值(通常刪除末尾對)
dict.clear() : 清空字典內容 flask
service = {
'http':80,
'ftp':23,
'ssh':22
}
item = service.pop('http') 過指定存在的key刪除對應的元素
print(item) 刪除最後一個key-value值
print(service) tomcat
#清空字典內容
service.clear()
print(service)oracle
5.字典的查看ssh
service = {
'http':80,
'ftp':23,
'ssh':22
}
#查看字典的key值
print(service.keys())
#查看字典的value值
print(service.values())
#查看字典的key-value值
print(service.items())
key不存在,默認返回None
key存在,default就返回defalut的值 沒有就返回None
print(service.get('ftp','23')) 使用get()查看key的value值,當key存在的時候,返回對應的value值,當key不存在的時候,返回一個設定好的默認值或者None。ide
dict.items() # 查看字典的鍵值對,生成一個新的列表,新列表的每個元素都爲一個元組,改元組中存放的是一個鍵值對。
dict.keys() # 生成一個列表,列表中的元素爲字典中的key
dict.values() # 查看字典的value值,生成一個新的列表,元素爲字典中的全部value函數