python中的字典

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'])

python中的字典

3.字典元素的增加

service = {
'http':80,
'ftp':23,
'ssh':22
}
#增加一個元素
#如果key值存在,則更新對應的value值
#如果key值不存在,則添加對應的key-value值
service['https'] = 443
print(service)
service['ftp'] = 21
print(service)
python中的字典
#增加多個key值
service_backup = {
'tomcat':8080,
'mysql':3306
}
service.update(service_backup)
print(service)
service.update(flask=9000,dns=53)
print(service)
python中的字典
#如果key值存在:不做修改
#如果key值不存在:則添加對應的key-value
service.setdefault('http',9090)
print(service)
service.setdefault('oracle',44575)
print(service)
python中的字典

4.字典元素的刪除
dict.pop(key) :通過key刪除指定的元素,並且刪除的元素可以被變量接收,當key存在的時候,成功刪除,當key不存在的時候,直接報錯
dict.popitem() 隨機返回並刪除字典中的一對鍵和值(一般刪除末尾對)
dict.clear() : 清空字典內容

service = {
'http':80,
'ftp':23,
'ssh':22
}
item = service.pop('http') 過指定存在的key刪除對應的元素
print(item) 刪除最後一個key-value值
print(service)

#清空字典內容
service.clear()
print(service)
python中的字典

5.字典的查看

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。
python中的字典

dict.items() # 查看字典的鍵值對,生成一個新的列表,新列表的每一個元素都爲一個元組,改元組中存放的是一個鍵值對。
dict.keys() # 生成一個列表,列表中的元素爲字典中的key
dict.values() # 查看字典的value值,生成一個新的列表,元素爲字典中的所有value

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章