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'
... }

可以使用內置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'
... )
字典內容的顯示。
>>> 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ù)等內置對象
>>> 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
同一字典內重復的鍵無法添加,如果添加則對原鍵的值進行替換。
>>> 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
運算符和內置函數(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
內置字典方法
與字符串和列表一樣字典上也是有調用內置方法。

# 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 字典內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
使用python創(chuàng)建股票的時間序列可視化分析
這篇文章主要為大家詳細介紹了python創(chuàng)建股票的時間序列可視化分析,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助2022-03-03
pytorch中tensor.expand()和tensor.expand_as()函數(shù)詳解
今天小編就為大家分享一篇pytorch中tensor.expand()和tensor.expand_as()函數(shù)詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-12-12
Python利用PyAutoGUI模塊實現(xiàn)控制鼠標鍵盤
PyAutoGUI是一個簡單易用,跨平臺的可以模擬鍵盤鼠標進行自動操作的python庫。本文將詳細講講它是如何實現(xiàn)控制鼠標鍵盤的,感興趣的可以了解一下2022-06-06
Python實現(xiàn)求最大公約數(shù)及判斷素數(shù)的方法
這篇文章主要介紹了Python實現(xiàn)求最大公約數(shù)及判斷素數(shù)的方法,涉及Python算數(shù)運算的相關技巧,需要的朋友可以參考下2015-05-05
Python基于keras訓練實現(xiàn)微笑識別的示例詳解
Keras是一個由Python編寫的開源人工神經(jīng)網(wǎng)絡庫,可用于深度學習模型的設計、調試、評估、應用和可視化。本文將基于keras訓練實現(xiàn)微笑識別效果,需要的可以參考一下2022-01-01
pytorch 在網(wǎng)絡中添加可訓練參數(shù),修改預訓練權重文件的方法
今天小編就為大家分享一篇pytorch 在網(wǎng)絡中添加可訓練參數(shù),修改預訓練權重文件的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-08-08
Python使用POP3和SMTP協(xié)議收發(fā)郵件的示例代碼
這篇文章主要介紹了Python使用POP3和SMTP協(xié)議收發(fā)郵件的示例代碼,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-04-04

