Python必備技巧之字典(Dictionary)詳解
Python中的字典由于是對(duì)象的集合屬于復(fù)合數(shù)據(jù)類型,類似于列表。
定義字典
字典是 Python 對(duì)數(shù)據(jù)結(jié)構(gòu)的實(shí)現(xiàn),通常稱為關(guān)聯(lián)數(shù)組。字典由鍵值對(duì)的集合組成。每個(gè)鍵值對(duì)將鍵映射到其關(guān)聯(lián)的值。
可以通過(guò)將逗號(hào)分隔的鍵值對(duì)列表括在花括號(hào) ( {} ) 中來(lái)定義字典。冒號(hào) ( : ) 將每個(gè)鍵與其關(guān)聯(lián)的值分開(kāi)。
d = { <key>: <value>, <key>: <value>, . . . <key>: <value> } # 定義一個(gè)Team >>> MLB_team = { ... 'Colorado' : 'Rockies', ... 'Boston' : 'Red Sox', ... 'Minnesota': 'Twins', ... 'Milwaukee': 'Brewers', ... 'Seattle' : 'Mariners' ... }
可以使用內(nèi)置dict()函數(shù)構(gòu)建字典。
d = dict([ (<key>, <value>), (<key>, <value), . . . (<key>, <value>) ]) # 定義一個(gè)Team >>> MLB_team = dict([ ... ('Colorado', 'Rockies'), ... ('Boston', 'Red Sox'), ... ('Minnesota', 'Twins'), ... ('Milwaukee', 'Brewers'), ... ('Seattle', 'Mariners') ... ]) # 另一種定義方式 >>> MLB_team = dict( ... Colorado='Rockies', ... Boston='Red Sox', ... Minnesota='Twins', ... Milwaukee='Brewers', ... Seattle='Mariners' ... )
字典內(nèi)容的顯示。
>>> type(MLB_team) <class 'dict'> >>> MLB_team {'Colorado': 'Rockies', 'Boston': 'Red Sox', 'Minnesota': 'Twins', 'Milwaukee': 'Brewers', 'Seattle': 'Mariners'}
字典中的條目按定義的順序顯示,使用索引無(wú)法指定訪問(wèn)元素。
>>> MLB_team[1] Traceback (most recent call last): File "<pyshell#13>", line 1, in <module> MLB_team[1] KeyError: 1
字典的訪問(wèn)
通過(guò)在方括號(hào)[]中指定對(duì)應(yīng)的鍵,從字典中檢索值。
>>> MLB_team['Minnesota'] 'Twins' >>> MLB_team['Colorado'] 'Rockies'
檢索值不在字典中則拋出異常。
>>> MLB_team['Toronto'] Traceback (most recent call last): File "<pyshell#19>", line 1, in <module> MLB_team['Toronto'] KeyError: 'Toronto'
現(xiàn)有字典添加數(shù)據(jù)只需分配新的鍵和值。
>>> MLB_team['Kansas City'] = 'Royals' >>> MLB_team {'Colorado': 'Rockies', 'Boston': 'Red Sox', 'Minnesota': 'Twins', 'Milwaukee': 'Brewers', 'Seattle': 'Mariners', 'Kansas City': 'Royals'}
更新數(shù)據(jù),只需為現(xiàn)有鍵分配一個(gè)新值。
>>> MLB_team['Seattle'] = 'Seahawks' >>> MLB_team {'Colorado': 'Rockies', 'Boston': 'Red Sox', 'Minnesota': 'Twins', 'Milwaukee': 'Brewers', 'Seattle': 'Seahawks', 'Kansas City': 'Royals'}
刪除數(shù)據(jù),使用 del 指定要?jiǎng)h除的鍵。
>>> del MLB_team['Seattle'] >>> MLB_team {'Colorado': 'Rockies', 'Boston': 'Red Sox', 'Minnesota': 'Twins', 'Milwaukee': 'Brewers', 'Kansas City': 'Royals'}
字典鍵與列表索引
經(jīng)常遇見(jiàn)的一些錯(cuò)誤做法。
>>> MLB_team['Toronto'] Traceback (most recent call last): File "<pyshell#8>", line 1, in <module> MLB_team['Toronto'] KeyError: 'Toronto' >>> MLB_team[1] Traceback (most recent call last): File "<pyshell#9>", line 1, in <module> MLB_team[1] KeyError: 1 # 數(shù)字作為鍵值使用 >>> d = {0: 'a', 1: 'b', 2: 'c', 3: 'd'} >>> d {0: 'a', 1: 'b', 2: 'c', 3: 'd'} >>> d[0] 'a' >>> d[2] 'c'
不能將字典視為列表。
>>> type(d) <class 'dict'> >>> d[-1] Traceback (most recent call last): File "<pyshell#30>", line 1, in <module> d[-1] KeyError: -1 >>> d[0:2] Traceback (most recent call last): File "<pyshell#31>", line 1, in <module> d[0:2] TypeError: unhashable type: 'slice' >>> d.append('e') Traceback (most recent call last): File "<pyshell#32>", line 1, in <module> d.append('e') AttributeError: 'dict' object has no attribute 'append'
增量構(gòu)建字典
創(chuàng)建新的空字典,然后通過(guò)一次添加一個(gè)新的鍵和值構(gòu)建。
>>> person = {} >>> type(person) <class 'dict'> >>> person['fname'] = 'Joe' >>> person['lname'] = 'Fonebone' >>> person['age'] = 51 >>> person['spouse'] = 'Edna' >>> person['children'] = ['Ralph', 'Betty', 'Joey'] >>> person['pets'] = {'dog': 'Fido', 'cat': 'Sox'} # 創(chuàng)建和訪問(wèn)字典 >>> person {'fname': 'Joe', 'lname': 'Fonebone', 'age': 51, 'spouse': 'Edna', 'children': ['Ralph', 'Betty', 'Joey'], 'pets': {'dog': 'Fido', 'cat': 'Sox'}} >>> person['fname'] 'Joe' >>> person['age'] 51 >>> person['children'] ['Ralph', 'Betty', 'Joey'] # 檢索字典數(shù)據(jù) >>> person['children'][-1] 'Joey' >>> person['pets']['cat'] 'Sox'
構(gòu)建的字典中數(shù)據(jù)類型沒(méi)有明確的限制。
>>> foo = {42: 'aaa', 2.78: 'bbb', True: 'ccc'} >>> foo {42: 'aaa', 2.78: 'bbb', True: 'ccc'} >>> foo[42] 'aaa' >>> foo[2.78] 'bbb' >>> foo[True] 'ccc'
字典鍵的限制
幾乎任何類型的值都可以用作 Python 中的字典鍵。
>>> foo = {42: 'aaa', 2.78: 'bbb', True: 'ccc'} >>> foo {42: 'aaa', 2.78: 'bbb', True: 'ccc'} # 可以使用類型和函數(shù)等內(nèi)置對(duì)象 >>> d = {int: 1, float: 2, bool: 3} >>> d {<class 'int'>: 1, <class 'float'>: 2, <class 'bool'>: 3} >>> d[float] 2 >>> d = {bin: 1, hex: 2, oct: 3} >>> d[oct] 3
同一字典內(nèi)重復(fù)的鍵無(wú)法添加,如果添加則對(duì)原鍵的值進(jìn)行替換。
>>> MLB_team = { ... 'Colorado' : 'Rockies', ... 'Boston' : 'Red Sox', ... 'Minnesota': 'Twins', ... 'Milwaukee': 'Brewers', ... 'Seattle' : 'Mariners' ... } >>> MLB_team['Minnesota'] = 'Timberwolves' >>> MLB_team {'Colorado': 'Rockies', 'Boston': 'Red Sox', 'Minnesota': 'Timberwolves', 'Milwaukee': 'Brewers', 'Seattle': 'Mariners'}
元組也可以是字典鍵,因?yàn)樵M是不可變的。
>>> d = {(1, 1): 'a', (1, 2): 'b', (2, 1): 'c', (2, 2): 'd'} >>> d[(1,1)] 'a' >>> d[(2,1)] 'c'
字典值的限制
字典的中的值是沒(méi)有任何限制的。
>>> d = {0: 'a', 1: 'a', 2: 'a', 3: 'a'} >>> d {0: 'a', 1: 'a', 2: 'a', 3: 'a'} >>> d[0] == d[1] == d[2] True
運(yùn)算符和內(nèi)置函數(shù)
in and not in運(yùn)算符返回True or False。
>>> MLB_team = { ... 'Colorado' : 'Rockies', ... 'Boston' : 'Red Sox', ... 'Minnesota': 'Twins', ... 'Milwaukee': 'Brewers', ... 'Seattle' : 'Mariners' ... } >>> 'Milwaukee' in MLB_team True >>> 'Toronto' in MLB_team False >>> 'Toronto' not in MLB_team True
也可以與短路評(píng)估一起使用。
>>> MLB_team['Toronto'] Traceback (most recent call last): File "<pyshell#2>", line 1, in <module> MLB_team['Toronto'] KeyError: 'Toronto' >>> 'Toronto' in MLB_team and MLB_team['Toronto'] False
內(nèi)置字典方法
與字符串和列表一樣字典上也是有調(diào)用內(nèi)置方法。
# d.clear() 清空字典數(shù)據(jù) >>> d = {'a': 10, 'b': 20, 'c': 30} >>> d {'a': 10, 'b': 20, 'c': 30} >>> d.clear() >>> d {} # d.get(<key>[, <default>]) 如果字典中存在鍵,則返回該鍵的值 >>> d = {'a': 10, 'b': 20, 'c': 30} >>> print(d.get('b')) 20 >>> print(d.get('z')) None # <key>未找到并且<default>指定了可選參數(shù) >>> print(d.get('z', -1)) -1 # d.items() 返回字典中的鍵值對(duì)列表 >>> d = {'a': 10, 'b': 20, 'c': 30} >>> d {'a': 10, 'b': 20, 'c': 30} >>> list(d.items()) [('a', 10), ('b', 20), ('c', 30)] >>> list(d.items())[1][0] 'b' >>> list(d.items())[1][1] 20 # d.keys() 返回字典中的鍵列表 >>> d = {'a': 10, 'b': 20, 'c': 30} >>> d {'a': 10, 'b': 20, 'c': 30} >>> list(d.keys()) ['a', 'b', 'c'] # d.values() 返回字典中的值列表 >>> d = {'a': 10, 'b': 20, 'c': 30} >>> d {'a': 10, 'b': 20, 'c': 30} >>> list(d.values()) [10, 20, 30] # d.pop(<key>[, <default>]) 從字典中刪除一個(gè)鍵,如果存在并返回它的值 >>> d = {'a': 10, 'b': 20, 'c': 30} >>> d.pop('b') 20 >>> d {'a': 10, 'c': 30} # 如果不存在則引發(fā)異常 >>> d = {'a': 10, 'b': 20, 'c': 30} >>> d.pop('z') Traceback (most recent call last): File "<pyshell#4>", line 1, in <module> d.pop('z') KeyError: 'z' # 如果指定默認(rèn)參數(shù)<default>則返回該值 >>> d = {'a': 10, 'b': 20, 'c': 30} >>> d.pop('z', -1) -1 >>> d {'a': 10, 'b': 20, 'c': 30} # d.popitem() 從字典中刪除鍵值對(duì) >>> d = {'a': 10, 'b': 20, 'c': 30} >>> d.popitem() ('c', 30) >>> d {'a': 10, 'b': 20} >>> d.popitem() ('b', 20) >>> d {'a': 10} # d為空會(huì)引發(fā)異常 >>> d = {} >>> d.popitem() Traceback (most recent call last): File "<pyshell#11>", line 1, in <module> d.popitem() KeyError: 'popitem(): dictionary is empty' # d.update(<obj>) 將字典與另一個(gè)字典或可迭代的鍵值對(duì)合并 # (被替換鍵值).update(替換鍵值) >>> d1 = {'a': 10, 'b': 20, 'c': 30} >>> d2 = {'b': 200, 'd': 400} >>> d1.update(d2) >>> d1 {'a': 10, 'b': 200, 'c': 30, 'd': 400} # 使用元組更新 >>> d1 = {'a': 10, 'b': 20, 'c': 30} >>> d1.update([('b', 200), ('d', 400)]) >>> d1 {'a': 10, 'b': 200, 'c': 30, 'd': 400} # 指定關(guān)鍵字參數(shù) >>> d1 = {'a': 10, 'b': 20, 'c': 30} >>> d1.update(b=200, d=400) >>> d1 {'a': 10, 'b': 200, 'c': 30, 'd': 400}
到此這篇關(guān)于Python必備技巧之字典(Dictionary)詳解的文章就介紹到這了,更多相關(guān)Python 字典內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
詳解python架構(gòu)?PyNeuraLogic超越Transformers
這篇文章主要為大家介紹了python使用?PyNeuraLogic超越Transformers示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-03-03Python Charles抓包配置實(shí)現(xiàn)流程圖解
這篇文章主要介紹了Python Charles抓包實(shí)現(xiàn)流程圖解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-09-09Python實(shí)現(xiàn)從訂閱源下載圖片的方法
這篇文章主要介紹了Python實(shí)現(xiàn)從訂閱源下載圖片的方法,涉及Python采集的技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-03-03Python循環(huán)語(yǔ)句中else的用法總結(jié)
這篇文章給大家整理了關(guān)于Python中循環(huán)語(yǔ)句中else的用法,包括常規(guī)的 if else 用法、if else 快捷用法、與 for 關(guān)鍵字一起用、與 while 關(guān)鍵字一起用以及與 try except 一起用的用法總結(jié),有需要的朋友們可以參考借鑒。2016-09-09Python OpenCV 圖像區(qū)域輪廓標(biāo)記(框選各種小紙條)
這篇文章主要介紹了Python OpenCV 圖像區(qū)域輪廓標(biāo)記(框選各種小紙條),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-03-03python通過(guò)shutil實(shí)現(xiàn)快速文件復(fù)制的方法
這篇文章主要介紹了python通過(guò)shutil實(shí)現(xiàn)快速文件復(fù)制的方法,涉及Python中shutil模塊的使用技巧,需要的朋友可以參考下2015-03-03打印tensorflow恢復(fù)模型中所有變量與操作節(jié)點(diǎn)方式
這篇文章主要介紹了打印tensorflow恢復(fù)模型中所有變量與操作節(jié)點(diǎn)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-05-05python3.6連接MySQL和表的創(chuàng)建與刪除實(shí)例代碼
這篇文章主要介紹了python3.6連接MySQL和表的創(chuàng)建與刪除實(shí)例代碼,具有一定借鑒價(jià)值,需要的朋友可以參考下2017-12-12