Python必備技巧之字典(Dictionary)詳解
Python中的字典由于是對象的集合屬于復合數(shù)據(jù)類型,類似于列表。
定義字典
字典是 Python 對數(shù)據(jù)結構的實現(xiàn),通常稱為關聯(lián)數(shù)組。字典由鍵值對的集合組成。每個鍵值對將鍵映射到其關聯(lián)的值。
可以通過將逗號分隔的鍵值對列表括在花括號 ( {} ) 中來定義字典。冒號 ( : ) 將每個鍵與其關聯(lián)的值分開。
d = { <key>: <value>, <key>: <value>, . . . <key>: <value> } # 定義一個Team >>> MLB_team = { ... 'Colorado' : 'Rockies', ... 'Boston' : 'Red Sox', ... 'Minnesota': 'Twins', ... 'Milwaukee': 'Brewers', ... 'Seattle' : 'Mariners' ... }
可以使用內(nèi)置dict()函數(shù)構建字典。
d = dict([ (<key>, <value>), (<key>, <value), . . . (<key>, <value>) ]) # 定義一個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'}
字典中的條目按定義的順序顯示,使用索引無法指定訪問元素。
>>> MLB_team[1] Traceback (most recent call last): File "<pyshell#13>", line 1, in <module> MLB_team[1] KeyError: 1
字典的訪問
通過在方括號[]中指定對應的鍵,從字典中檢索值。
>>> 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)有鍵分配一個新值。
>>> MLB_team['Seattle'] = 'Seahawks' >>> MLB_team {'Colorado': 'Rockies', 'Boston': 'Red Sox', 'Minnesota': 'Twins', 'Milwaukee': 'Brewers', 'Seattle': 'Seahawks', 'Kansas City': 'Royals'}
刪除數(shù)據(jù),使用 del 指定要刪除的鍵。
>>> del MLB_team['Seattle'] >>> MLB_team {'Colorado': 'Rockies', 'Boston': 'Red Sox', 'Minnesota': 'Twins', 'Milwaukee': 'Brewers', 'Kansas City': 'Royals'}
字典鍵與列表索引
經(jīng)常遇見的一些錯誤做法。
>>> 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'
增量構建字典
創(chuàng)建新的空字典,然后通過一次添加一個新的鍵和值構建。
>>> 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)建和訪問字典 >>> 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'
構建的字典中數(shù)據(jù)類型沒有明確的限制。
>>> 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)置對象 >>> 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)重復的鍵無法添加,如果添加則對原鍵的值進行替換。
>>> 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'}
元組也可以是字典鍵,因為元組是不可變的。
>>> d = {(1, 1): 'a', (1, 2): 'b', (2, 1): 'c', (2, 2): 'd'} >>> d[(1,1)] 'a' >>> d[(2,1)] 'c'
字典值的限制
字典的中的值是沒有任何限制的。
>>> 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
運算符和內(nèi)置函數(shù)
in and not in運算符返回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
也可以與短路評估一起使用。
>>> 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() 返回字典中的鍵值對列表 >>> 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>]) 從字典中刪除一個鍵,如果存在并返回它的值 >>> 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' # 如果指定默認參數(shù)<default>則返回該值 >>> d = {'a': 10, 'b': 20, 'c': 30} >>> d.pop('z', -1) -1 >>> d {'a': 10, 'b': 20, 'c': 30} # d.popitem() 從字典中刪除鍵值對 >>> d = {'a': 10, 'b': 20, 'c': 30} >>> d.popitem() ('c', 30) >>> d {'a': 10, 'b': 20} >>> d.popitem() ('b', 20) >>> d {'a': 10} # d為空會引發(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>) 將字典與另一個字典或可迭代的鍵值對合并 # (被替換鍵值).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} # 指定關鍵字參數(shù) >>> d1 = {'a': 10, 'b': 20, 'c': 30} >>> d1.update(b=200, d=400) >>> d1 {'a': 10, 'b': 200, 'c': 30, 'd': 400}
到此這篇關于Python必備技巧之字典(Dictionary)詳解的文章就介紹到這了,更多相關Python 字典內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
詳解python架構?PyNeuraLogic超越Transformers
這篇文章主要為大家介紹了python使用?PyNeuraLogic超越Transformers示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-03-03Python Charles抓包配置實現(xiàn)流程圖解
這篇文章主要介紹了Python Charles抓包實現(xiàn)流程圖解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-09-09Python OpenCV 圖像區(qū)域輪廓標記(框選各種小紙條)
這篇文章主要介紹了Python OpenCV 圖像區(qū)域輪廓標記(框選各種小紙條),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2021-03-03python通過shutil實現(xiàn)快速文件復制的方法
這篇文章主要介紹了python通過shutil實現(xiàn)快速文件復制的方法,涉及Python中shutil模塊的使用技巧,需要的朋友可以參考下2015-03-03打印tensorflow恢復模型中所有變量與操作節(jié)點方式
這篇文章主要介紹了打印tensorflow恢復模型中所有變量與操作節(jié)點方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-05-05python3.6連接MySQL和表的創(chuàng)建與刪除實例代碼
這篇文章主要介紹了python3.6連接MySQL和表的創(chuàng)建與刪除實例代碼,具有一定借鑒價值,需要的朋友可以參考下2017-12-12