1. 程式人生 > >字典的建立,特性,增加,刪除以及修改與檢視

字典的建立,特性,增加,刪除以及修改與檢視

1.字典的建立
以key-value 鍵值對儲存的一種資料結構
#value值可以是任意資料型別:int float long list set tuple dict
d = {
‘1’:‘a’,
‘8’:‘b’,
‘2’:‘a’
}
字典的巢狀
students = {
‘xuehao’:{
‘name’:‘zhangsan’,
‘age’:18,
‘score’:90
},
‘xuehao1’:{
‘name’:‘lisi’,
‘age’:18,
‘score’:88
},
}
print(students[‘xuehao’][‘name’])

注意:字典不支援索引和切片,字典的重複和連線是無意義的,字典的key是唯一的

字典的操作符:判斷的是某個值是否為字典的key

d = {
‘1’:‘a’
‘8’:‘b’
}
print(‘1’ in d)
print(‘2’ not in d)
print(d[‘1’]) #其實輸出的是key值對應value
工廠函式
d5 = dict(a=1,b=2)
print(d5)
字典的for迴圈,預設遍歷字典的key值
for key in d5:
print(key) 遍歷輸出字典的key值
遍歷字典
for key in d5:
print(key,d5[key]) 遍歷輸出字典的key-value值
在這裡插入圖片描述

service = {
‘http’:80,
‘ftp’:21,
‘ssh’:22
}

1,增加一個元素

1),如果key值存在,則更新對應的value值
2),如果key值不存在,則新增對應的key-value值
service[‘mysql’]=3306
service[‘http’]=32
print(service)
2,新增多個key-value值
1),如果key值存在,則更新對應的value值
2),如果key值不存在,則新增對應的key-value值
service={
‘tomact’:8080,
‘https’:43,
‘http’:888
}
service.update(flask=9000,http=222)
print(service)
3.setdefault新增key值:
1),如果key值存在,則不做修改
2),如果key值不存在,則新增對應的key-value值
service.setdefault(‘httpd’,9000)
print(service)

1,刪除字典中的內容
1)del關鍵字
del service[‘http’]
print(‘service’)
2,pop刪除指定key的key-value值
1)如果key存在,刪除,(並且返回刪除key對應的value值)
2)如果key不存在,直接報錯
item = service.pop(‘http’)
print(item) 可以打印出刪除的key對應的value值
print(service)
在這裡插入圖片描述
3.popitem刪除最後一個key-value
item1=service.popitem()
print(service)

4.清空字典內容
service.clear()
print(service)

檢視字典裡面所有的key值

print(service.keys())

檢視字典裡面所有的value值

print(service.values())

檢視指定key對應的value值

print(service[‘http’])
#遍歷字典
for k,v in service.items():
print(k,’—>’,v)

get方法獲取指定key對應的value值 如果key值存在,返回對應的value值 如果key值不存在,預設返回None

print(service.get(‘https’))

fromkeys
用於建立一個新字典,以序列seq中元素做字典的鍵,value為字典所有鍵對應的初始值。第一個引數可以是 list/tuple/str/set
fromkeys()方法語法:

dict.fromkeys(seq,[value])

seq = (‘name’, ‘age’, ‘sex’)
dict = dict.fromkeys(seq, 10)
print (“新的字典為 : %s” % str(dict))
輸出結果為
新的字典為 : {‘age’: 10, ‘name’: 10, ‘sex’: 10}