07-字典

字典

特點(diǎn):
1)不允許同一個(gè)鍵出現(xiàn)兩次。創(chuàng)建時(shí)如果同一個(gè)鍵被賦值兩次,后一個(gè)值會(huì)被記住
2)鍵必須不可變,所以可以用數(shù)字,字符串或元組充當(dāng),而用列表就不行


1.創(chuàng)建字典

注意:字典的鍵只能是數(shù)字、字符串或者元組 (不能是列表。列表是可變的,不能作為鍵 ),需要注意的是,同一字典中的各個(gè)鍵必須唯一,不能重復(fù)。

1. 1 使用 { } 創(chuàng)建字典

語法格式:dict = { 'key': 'value1', 'key2': 'value2', ... }

key : 鍵 (唯一和不可變的特性)

value : 值

# 創(chuàng)建空元組
 dict = {}
 print(dict)  # out: {}
 ?
# 使用字符串作為key
 grade = {'數(shù)學(xué)': 95, '英語': 92, '語文': 84}
 print(grade)  # out: {'數(shù)學(xué)': 95, '英語': 92, '語文': 84}
 ?
# 使用元組和數(shù)字作為key
 dict1 = {(20, 30): 'great', 30: [1, 2, 3]}
 print(dict1)  # out: {(20, 30): 'great', 30: [1, 2, 3]}


1. 2 通過 fromkeys() 方法創(chuàng)建字典

語法格式:dict = dict.fromkeys(list, value=None)

list 參數(shù)表示字典中所有鍵的列表(list)
value 參數(shù)表示默認(rèn)值,如果不寫,則為空值 None。

 subject = {'語文', '數(shù)學(xué)', '英語'}
 grade= dict.fromkeys(subject, 60)
 print(grade)  # out: {'語文': 60, '英語': 60, '數(shù)學(xué)': 60}


1. 3 通過 dict() 映射函數(shù)創(chuàng)建字典
'''str 表示字符串類型的鍵,value 表示鍵對(duì)應(yīng)的值。使用此方式創(chuàng)建字典時(shí),字符串不能帶引號(hào)。'''
 a = dict(str1=value1, str2=value2, str3=value3)
 # 創(chuàng)建空字典
 d = dict()
 print(d)  # out: {}


'''②向 dict() 函數(shù)傳入列表或元組,而它們中的元素又各自是包含 2 個(gè)元素的列表或元組,其中第一個(gè)元素作為鍵,第二個(gè)元素作為值。'''
 # 方式1 列表套元組
 demo = [('two', 2), ('one', 1), ('three', 3)]  
 # 方式2 列表套列表
 demo = [['two', 2], ['one', 1], ['three', 3]]
 # 方式3 元組套元組
 demo = (('two', 2), ('one', 1), ('three', 3))
 # 方式4 元組套列表
 demo = (['two', 2], ['one', 1], ['three', 3])
 a = dict(demo)
 print(a)  # out: {'two': 2, 'one': 1, 'three': 3}


'''③通過應(yīng)用 dict() 函數(shù)和 zip() 函數(shù),可將前兩個(gè)列表轉(zhuǎn)換為對(duì)應(yīng)的字典。'''
 keys = ['one', 'two', 'three']  # 還可以是字符串或元組
 values = [1, 2, 3]  # 還可以是字符串或元組
 a = dict( zip(keys, values) )


2.訪問字典

2. 1 通過鍵來訪問對(duì)應(yīng)的值

語法格式:dict_name[key]

dict_name : 表示字典變量的名字
key : 表示鍵名
注意,鍵必須是存在的,否則會(huì)拋出異常。

 tup = (['two', 26],  ['one', 88],  ['three', 100],  ['four', -59])
 dic = dict(tup)
 print(dic['one'])  # 鍵存在, 88
 print(dic['five'])  # 鍵不存在,報(bào)錯(cuò)


2. 2 通過get()方法獲取

語法格式:dict_name.get( '鍵名' )

 a = dict(two=0.65, one=88, three=100, four=-59)
 print( a.get('one') )  # out: 88
 ?
 '''當(dāng)鍵不存在時(shí),get()返回空值None,如果想明確地提示用戶該鍵不存在,那么可以手動(dòng)設(shè)置 get()的第二個(gè)參數(shù)'''
 a = dict(two=0.65, one=88, three=100, four=-59)
 print( a.get('five',  '該鍵不存在') )  # out: 該鍵不存在


3.刪除操作

語法格式:del dict_name

 '''刪除字典'''
 a = dict(two=0.65, one=88, three=100, four=-59)
 print(a)  # out: {'two': 0.65, 'one': 88, 'three': 100, 'four': -59}
 del a
 print(a)  # 報(bào)錯(cuò), 字典a已經(jīng)被刪除了
 ?
 ?
 '''刪除字典中的鍵值對(duì)'''
 a = {'數(shù)學(xué)': 95, '語文': 89, '英語': 90}
 del a['語文']
 del a['數(shù)學(xué)']
 print(a)  # out: {'英語': 90}


4. 修改操作

語法格式:dict_name[key] = value

 a = {'數(shù)學(xué)':95}
 print(a)  # out: {'數(shù)學(xué)': 95}
 # 添加新鍵值對(duì)
 a['語文'] = 89
 print(a)  # out: {'數(shù)學(xué)': 95, '語文': 89}
 # 再次添加新鍵值對(duì)
 a['英語'] = 90
 print(a)  # out: {'數(shù)學(xué)': 95, '語文': 89, '英語': 90}
 ?
 ?
 '''字典中鍵(key)的名字不能被修改,我們只能修改值(value)'''
 a = {'數(shù)學(xué)': 95, '語文': 89, '英語': 90}
 print(a)  # out: {'數(shù)學(xué)': 95, '語文': 89, '英語': 90}
 a['語文'] = 100
 print(a)  # out: {'數(shù)學(xué)': 95, '語文': 100, '英語': 90}
 # 可以看到,字典中沒有再添加一個(gè){'語文': 100}鍵值對(duì),而是對(duì)原有鍵值對(duì){'語文': 89}中的 value 做了修改。


5. 常用方法

5. 1 keys()、values() 和 items() 方法
  • keys() 方法用于返回字典中的所有鍵(key);

  • values() 方法用于返回字典中所有鍵對(duì)應(yīng)的值(value);

  • items() 方法用于返回字典中所有的鍵值對(duì)(key-value)。

 scores = {'數(shù)學(xué)': 95, '語文': 89, '英語': 90}
 print(scores.keys())  # out: dict_keys(['數(shù)學(xué)', '語文', '英語'])
 print(scores.values())  # out: dict_values([95, 89, 90])
 print(scores.items())  # out: dict_items([('數(shù)學(xué)', 95), ('語文', 89), ('英語', 90)])

在 Python 2.x 中,上面三個(gè)方法的返回值都是列表(list)類型。但在 Python 3.x 中,它們的返回值并不是我們常見的列表或者元組類型,因?yàn)?Python 3.x 不希望用戶直接操作這幾個(gè)方法的返回值。

在 Python 3.x 中如果想使用這三個(gè)方法返回的數(shù)據(jù),一般有下面兩種方案:

  1. 使用 list() 函數(shù),將它們返回的數(shù)據(jù)轉(zhuǎn)換成列表,例如:
 a = {'數(shù)學(xué)': 95, '語文': 89, '英語': 90}
 b = list(a.keys())
 print(b)  # out: ['數(shù)學(xué)', '語文', '英語']
  1. 使用 for in 循環(huán)遍歷它們的返回值,例如:
 a = {'數(shù)學(xué)': 95, '語文': 89, '英語': 90}
 for k in a.keys():
 print(k,end=' ')
 print("\n---------------")
 for v in a.values():
 print(v,end=' ')
 print("\n---------------")
 for k,v in a.items():
 print("key:",k," value:",v)

'''運(yùn)行結(jié)果為:

    數(shù)學(xué) 語文 英語  
    ---------------  
    95 89 90  
    ---------------  
    key: 數(shù)學(xué) value: 95  
    key: 語文 value: 89  
    key: 英語 value: 90

'''


5. 2 copy() 方法

作用:返回一個(gè)字典的拷貝,也即返回一個(gè)具有相同鍵值對(duì)的新字典

語法格式:dict_name.copy()

 a = {'one': 1, 'two': 2, 'three': [1, 2, 3]}
 b = a.copy()
 print(b)  # out: {'one': 1, 'two': 2, 'three': [1, 2, 3]}

可以看到,copy() 方法將字典 a 的數(shù)據(jù)全部拷貝給了字典 b。

注意:copy() 方法所遵循的拷貝原理,既有深拷貝,也有淺拷貝。拿拷貝字典 a 為例,copy() 方法只會(huì)對(duì)最表層的鍵值對(duì)進(jìn)行深拷貝,也就是說,它會(huì)再申請(qǐng)一塊內(nèi)存用來存放 {'one': 1, 'two': 2, 'three': []};而對(duì)于某些列表類型的值來說,此方法對(duì)其做的是淺拷貝,也就是說,b 中的 [1,2,3] 的值不是自己獨(dú)有,而是和 a 共有。

 a = {'one': 1, 'two': 2, 'three': [1, 2, 3]}
 b = a.copy()

# 向 a 中添加新鍵值對(duì),由于b已經(jīng)提前將 a 所有鍵值對(duì)都深拷貝過來,因此 a 添加新鍵值對(duì),不會(huì)影響 b。
 a['four']=100
 print(a)  # out: {'one': 1, 'two': 2, 'three': [1, 2, 3], 'four': 100}
 print(b)  # out: {'one': 1, 'two': 2, 'three': [1, 2, 3]}

# 由于 b 和 a 共享[1,2,3](淺拷貝),因此移除 a 中列表中的元素,也會(huì)影響 b。
 a['three'].remove(1)
 print(a)  # out: {'one': 1, 'two': 2, 'three': [2, 3], 'four': 100} 
 print(b)  # out: {'one': 1, 'two': 2, 'three': [2, 3]}

從運(yùn)行結(jié)果不難看出,對(duì) a 增加新鍵值對(duì),b 不變;而修改 a 某鍵值對(duì)中列表內(nèi)的元素,b也會(huì)相應(yīng)改變。


5. 3 update() 方法

作用:使用一個(gè)字典所包含的鍵值對(duì)來更新己有的字典。

在執(zhí)行 update() 方法時(shí),如果被更新的字典中己包含對(duì)應(yīng)的鍵值對(duì),那么原 value 會(huì)被覆蓋;如果被更新的字典中不包含對(duì)應(yīng)的鍵值對(duì),則該鍵值對(duì)被添加進(jìn)去。

語法格式:dict_name.update()

 a = {'one': 1, 'two': 2, 'three': 3}
 a.update({'one':4.5, 'four': 9.3})
 print(a)  # out: {'one': 4.5, 'two': 2, 'three': 3, 'four': 9.3}


5. 4 pop() 和 popitem() 方法

作用:pop() 和 popitem() 都用來刪除字典中的鍵值對(duì),不同的是,pop() 用來刪除指定的鍵值對(duì),而 popitem() 用來隨機(jī)刪除一個(gè)鍵值對(duì)。

語法格式:dict_name.pop(key) , dict_name.popitem()

 a = {'數(shù)學(xué)': 95, '語文': 89, '英語': 90, '化學(xué)': 83, '生物': 98, '物理': 89}
 print(a)
 a.pop('化學(xué)')
 print(a)  # out: {'數(shù)學(xué)': 95, '語文': 89, '英語': 90, '生物': 98, '物理': 89}
 a.popitem()
 print(a)  # out: {'數(shù)學(xué)': 95, '語文': 89, '英語': 90, '生物': 98}

對(duì) popitem() 的說明

其實(shí),說 popitem() 隨機(jī)刪除字典中的一個(gè)鍵值對(duì)是不準(zhǔn)確的,雖然字典是一種無須的列表,但鍵值對(duì)在底層也是有存儲(chǔ)順序的,popitem() 總是彈出底層中的最后一個(gè) key-value,這和列表的 pop() 方法類似,都實(shí)現(xiàn)了數(shù)據(jù)結(jié)構(gòu)中“出?!钡牟僮?。


5. 5 setdefault() 方法

作用:用來返回某個(gè) key 對(duì)應(yīng)的 value

語法格式:dict_name.setdefault(key, defaultvalue)

dictname 表示字典名稱,key 表示鍵,defaultvalue 表示默認(rèn)值(可以不寫,不寫的話是 None)。

當(dāng)指定的 key 不存在時(shí),setdefault() 會(huì)先為這個(gè)不存在的 key 設(shè)置一個(gè)默認(rèn)的 defaultvalue,然后再返回 defaultvalue。

也就是說,setdefault() 方法總能返回指定 key 對(duì)應(yīng)的 value:

如果該 key 存在,那么直接返回該 key 對(duì)應(yīng)的 value;
如果該 key 不存在,那么先為該 key 設(shè)置默認(rèn)的 defaultvalue,然后再返回該 key 對(duì)應(yīng)的 defaultvalue。

 a = {'數(shù)學(xué)': 95, '語文': 89, '英語': 90}
 print(a)  # out: {'數(shù)學(xué)': 95, '語文': 89, '英語': 90} 

# key不存在,指定默認(rèn)值
 a.setdefault('物理', 94)
 print(a)  # out: {'數(shù)學(xué)': 95, '語文': 89, '英語': 90, '物理': 94}

# key不存在,不指定默認(rèn)值
 a.setdefault('化學(xué)')
 print(a)  # out: {'數(shù)學(xué)': 95, '語文': 89, '英語': 90, '物理': 94, '化學(xué)': None}

# key存在,指定默認(rèn)值
 a.setdefault('數(shù)學(xué)', 100)
 print(a)  # out: {'數(shù)學(xué)': 95, '語文': 89, '英語': 90, '物理': 94, '化學(xué)': None}
5. 5 clear() 方法

作用:清除字典中的所有項(xiàng),無返回值

語法格式:dict_name.clear()

 a = {'數(shù)學(xué)': 95, '語文': 89, '英語': 90}
 a.clear()
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容