最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python必備技巧之字典(Dictionary)詳解

 更新時(shí)間:2022年03月24日 14:34:58   作者:Mr數(shù)據(jù)楊  
Python中的字典由于是對象的集合屬于復(fù)合數(shù)據(jù)類型,類似于列表。本文將通過示例詳細(xì)講解Python中字典的使用方法,感興趣的可以了解一下

Python中的字典由于是對象的集合屬于復(fù)合數(shù)據(jù)類型,類似于列表。

定義字典

字典是 Python 對數(shù)據(jù)結(jié)構(gòu)的實(shí)現(xiàn),通常稱為關(guān)聯(lián)數(shù)組。字典由鍵值對的集合組成。每個(gè)鍵值對將鍵映射到其關(guān)聯(lián)的值。

可以通過將逗號(hào)分隔的鍵值對列表括在花括號(hào) ( {} ) 中來定義字典。冒號(hào) ( : ) 將每個(gè)鍵與其關(guān)聯(lián)的值分開。

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

字典中的條目按定義的順序顯示,使用索引無法指定訪問元素。

>>> MLB_team[1]
Traceback (most recent call last):
  File "<pyshell#13>", line 1, in <module>
    MLB_team[1]
KeyError: 1

字典的訪問

通過在方括號(hào)[]中指定對應(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)常遇見的一些錯(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)建新的空字典,然后通過一次添加一個(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)建和訪問字典
>>> 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ù)類型沒有明確的限制。

>>> 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)重復(fù)的鍵無法添加,如果添加則對原鍵的值進(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'

字典值的限制

字典的中的值是沒有任何限制的。

>>> 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

也可以與短路評估一起使用。

>>> 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>]) 從字典中刪除一個(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() 從字典中刪除鍵值對
>>> 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è)字典或可迭代的鍵值對合并
# (被替換鍵值).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)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 使用python創(chuàng)建股票的時(shí)間序列可視化分析

    使用python創(chuàng)建股票的時(shí)間序列可視化分析

    這篇文章主要為大家詳細(xì)介紹了python創(chuàng)建股票的時(shí)間序列可視化分析,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助
    2022-03-03
  • pytorch中tensor.expand()和tensor.expand_as()函數(shù)詳解

    pytorch中tensor.expand()和tensor.expand_as()函數(shù)詳解

    今天小編就為大家分享一篇pytorch中tensor.expand()和tensor.expand_as()函數(shù)詳解,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-12-12
  • Python利用PyAutoGUI模塊實(shí)現(xiàn)控制鼠標(biāo)鍵盤

    Python利用PyAutoGUI模塊實(shí)現(xiàn)控制鼠標(biāo)鍵盤

    PyAutoGUI是一個(gè)簡單易用,跨平臺(tái)的可以模擬鍵盤鼠標(biāo)進(jìn)行自動(dòng)操作的python庫。本文將詳細(xì)講講它是如何實(shí)現(xiàn)控制鼠標(biāo)鍵盤的,感興趣的可以了解一下
    2022-06-06
  • 詳解python算法之冒泡排序

    詳解python算法之冒泡排序

    這篇文章主要介紹了詳解python算法之冒泡排序,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-03-03
  • Python實(shí)現(xiàn)求最大公約數(shù)及判斷素?cái)?shù)的方法

    Python實(shí)現(xiàn)求最大公約數(shù)及判斷素?cái)?shù)的方法

    這篇文章主要介紹了Python實(shí)現(xiàn)求最大公約數(shù)及判斷素?cái)?shù)的方法,涉及Python算數(shù)運(yùn)算的相關(guān)技巧,需要的朋友可以參考下
    2015-05-05
  • Python基于keras訓(xùn)練實(shí)現(xiàn)微笑識(shí)別的示例詳解

    Python基于keras訓(xùn)練實(shí)現(xiàn)微笑識(shí)別的示例詳解

    Keras是一個(gè)由Python編寫的開源人工神經(jīng)網(wǎng)絡(luò)庫,可用于深度學(xué)習(xí)模型的設(shè)計(jì)、調(diào)試、評估、應(yīng)用和可視化。本文將基于keras訓(xùn)練實(shí)現(xiàn)微笑識(shí)別效果,需要的可以參考一下
    2022-01-01
  • python set集合使用方法解析

    python set集合使用方法解析

    這篇文章主要介紹了python set集合使用方法解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-11-11
  • Python TKinter如何自動(dòng)關(guān)閉主窗口

    Python TKinter如何自動(dòng)關(guān)閉主窗口

    這篇文章主要介紹了Python TKinter如何自動(dòng)關(guān)閉主窗口,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-02-02
  • pytorch 在網(wǎng)絡(luò)中添加可訓(xùn)練參數(shù),修改預(yù)訓(xùn)練權(quán)重文件的方法

    pytorch 在網(wǎng)絡(luò)中添加可訓(xùn)練參數(shù),修改預(yù)訓(xùn)練權(quán)重文件的方法

    今天小編就為大家分享一篇pytorch 在網(wǎng)絡(luò)中添加可訓(xùn)練參數(shù),修改預(yù)訓(xùn)練權(quán)重文件的方法,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-08-08
  • Python使用POP3和SMTP協(xié)議收發(fā)郵件的示例代碼

    Python使用POP3和SMTP協(xié)議收發(fā)郵件的示例代碼

    這篇文章主要介紹了Python使用POP3和SMTP協(xié)議收發(fā)郵件的示例代碼,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-04-04

最新評論

会宁县| 石台县| 周宁县| 连平县| 连南| 鄢陵县| 固安县| 台南市| 饶阳县| 常山县| 临澧县| 曲靖市| 永寿县| 龙泉市| 二连浩特市| 林芝县| 泰安市| 塔河县| 威信县| 苏州市| 达州市| 扎囊县| 敖汉旗| 金堂县| 临邑县| 云和县| 饶阳县| 尼勒克县| 堆龙德庆县| 闸北区| 晋城| 锡林浩特市| 堆龙德庆县| 珠海市| 和硕县| 广饶县| 四子王旗| 那曲县| 海原县| 和政县| 吉木萨尔县|