Python基礎練習與代碼示例之dict

dict是我非常喜歡的一種數據類型,我甚至基於這種映射的概念發明了新的詞組:KV編程論(後期有時間再說)。 dict在Python的代碼中用途非常廣泛,類似武術中的馬步,好好練習,習以爲常,能助你以後在代碼編寫過程中如魚得水,風生水起。

廢話少說,今天我們就來看看dict的基礎練習與代碼示例。

DE8UG的代碼環境爲:

  • Windows10
  • python3.7

概念

字典的基本創建格式:{鍵1: 值1,鍵2: 值2。。。},例如: {'jack': 4098, 'sjoerd': 4127} 或 {4098: 'jack', 4127: 'sjoerd'},大括號是必須的,裏面的各種符號,逗號,引號,冒號等都是英文符號。

注意:鍵的內容不能重複。且可變類型的值不能作爲鍵。因爲鍵的位置是需要唯一的,需要用它去映射後面的值。 更專業的說法是鍵需要是可hashable的。對於hashable,在官方文檔有解釋:

hashable -- 可哈希 一個對象的哈希值如果在其生命週期內絕不改變,就被稱爲 可哈希 (它需要具有 hash() 方法),並可以同其他對象進行比較(它需要具有 eq() 方法)。可哈希對象必須具有相同的哈希值比較結果纔會相同。 可哈希性使得對象能夠作爲字典鍵或集合成員使用,因爲這些數據結構要在內部使用哈希值。 大多數 Python 中的不可變內置對象都是可哈希的;可變容器(例如列表或字典)都不可哈希;不可變容器(例如元組和 frozenset)僅當它們的元素均爲可哈希時纔是可哈希的。 用戶定義類的實例對象默認是可哈希的。 它們在比較時一定不相同(除非是與自己比較),它們的哈希值的生成是基於它們的 id()。

除了使用{}創建字典,還可以用字典的類dict來生成新的字典對象。

dict類的構造形式有:

class dict(**kwarg)
class dict(mapping, **kwarg)
class dict(iterable, **kwarg)

於是,我們用{"one": 1, "two": 2, "three": 3}舉例,還可以有以下幾種格式建立新的字典

>>> a = dict(one=1, two=2, three=3)
>>> b = {'one': 1, 'two': 2, 'three': 3}
>>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
>>> d = dict([('two', 2), ('one', 1), ('three', 3)])
>>> e = dict({'three': 3, 'one': 1, 'two': 2})
>>> a == b == c == d == e
True    # 這裏直接用==判斷前面幾個字典變量是相同的

函數

下面我們先定義一個字典d,然後介紹字典的相關操作和代碼示例。

d = dict([('two', 2), ('one', 1), ('three', 3)])

<style> table th:first-of-type { width: 100px; } </style>

操作 含義
list(d) 返回字典 d 中使用的所有鍵的列表。
len(d) 返回字典 d 中的項數
d[key] 返回 d 中以 key 爲鍵的項。 如果映射中不存在 key 則會引發 KeyError。
d[key] = value 將 d[key] 設爲 value。
del d[key] 將 d[key] 從 d 中移除。 如果映射中不存在 key 則會引發 KeyError。
key in d 如果 d 中存在鍵 key 則返回 True,否則返回 False。
key not in d 等價於 not key in d。
iter(d) 返回以字典的鍵爲元素的迭代器。 這是 iter(d.keys()) 的快捷方式。
clear() 移除字典中的所有元素。
copy() 返回原字典的淺拷貝。
get(key[, default]) 如果 key 存在於字典中則返回 key 的值,否則返回 default。 如果 default 未給出則默認爲 None,因而此方法絕不會引發 KeyError。
items() 返回由字典項 ((鍵, 值) 對) 組成的一個新視圖。 參見 視圖對象文檔。
keys() 返回由字典鍵組成的一個新視圖。 參見 視圖對象文檔。
pop(key[, default]) 如果 key 存在於字典中則將其移除並返回其值,否則返回 default。 如果 default 未給出且 key 不存在於字典中,則會引發 KeyError。
popitem() 從字典中移除並返回一個 (鍵, 值) 對。 鍵值對會按 LIFO 的順序被返回。在 3.7 版更改: 現在會確保採用 LIFO 順序。 在之前的版本中,popitem() 會返回一個任意的鍵/值對。
reversed(d) 返回一個逆序獲取字典鍵的迭代器。 這是 reversed(d.keys()) 的快捷方式。注意,這個在python3.8才支持
setdefault(key[, default]) 如果字典存在鍵 key ,返回它的值。如果不存在,插入值爲 default 的鍵 key ,並返回 default 。 default 默認爲 None。
update([other]) 使用來自 other 的鍵/值對更新字典,覆蓋原有的鍵。 返回 None。update() 接受另一個字典對象,或者一個包含鍵/值對(以長度爲二的元組或其他可迭代對象表示)的可迭代對象。 如果給出了關鍵字參數,則會以其所指定的鍵/值對更新字典: d.update(red=1, blue=2)。
values() 返回由字典值組成的一個新視圖,在 3.7 版更改: 字典順序會確保爲插入順序

代碼示例:

這裏主要是兩種調用方式:

  • d作爲參數。比如func(d),表示python內置函數把字典作爲參數。
  • d作爲對象,調用字典自己的方法。比如d.func(...)
In [1]: d = dict([('two', 2), ('one', 1), ('three', 3)])

In [2]: list(d)
Out[2]: ['two', 'one', 'three']

In [3]: len(d)
Out[3]: 3

In [4]: d['two']
Out[4]: 2

In [5]: d['two']=222

In [6]: d['two']
Out[6]: 222

In [7]: del d['two']

In [8]: d
Out[8]: {'one': 1, 'three': 3}

In [9]: 'two' in d
Out[9]: False

In [10]: 'one' in d
Out[10]: True

In [11]: iter(d)
Out[11]: <dict_keyiterator at 0x192d1d4f2c8>

In [12]: dd=d.copy()

In [13]: dd
Out[13]: {'one': 1, 'three': 3}

In [14]: d.get('one')
Out[14]: 1

In [15]: d.keys()
Out[15]: dict_keys(['one', 'three'])

In [16]: d.items()
Out[16]: dict_items([('one', 1), ('three', 3)])

In [17]: d.pop()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-17-663961784a31> in <module>
----> 1 d.pop()

TypeError: pop expected at least 1 arguments, got 0

In [18]: d.pop('one')
Out[18]: 1

In [19]: d
Out[19]: {'three': 3}

In [20]: d['name']='de8ug'

In [21]: d['city']='beijing'

In [22]: d
Out[22]: {'three': 3, 'name': 'de8ug', 'city': 'beijing'}

In [23]: d.popitem()
Out[23]: ('city', 'beijing')

In [24]: d
Out[24]: {'three': 3, 'name': 'de8ug'}

In [25]: reversed(d)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-25-b13b185f39f7> in <module>
----> 1 reversed(d)

TypeError: 'dict' object is not reversible

注意,這裏的reversed函數出錯了,因爲我當前環境是python3.7,這個新的功能是在python3.8才生效。具體在:https://docs.python.org/3.8/whatsnew/3.8.html

Guido在信中有介紹: reversed() is supported for both dicts and dictviews since version 3.8 (14.10.2018).

這樣就讓字典變得有序,可以逆轉了。參考代碼:

>>> d = {"one": 1, "two": 2, "three": 3, "four": 4}
>>> d
{'one': 1, 'two': 2, 'three': 3, 'four': 4}
>>> list(reversed(d))
['four', 'three', 'two', 'one']
>>> list(reversed(d.values()))
[4, 3, 2, 1]
>>> list(reversed(d.items()))
[('four', 4), ('three', 3), ('two', 2), ('one', 1)]

你可以安裝python3.8試一下。

ok,希望上面的代碼你都自己練習一遍,這樣在以後用到某個方法時候才能知道怎麼回事兒。

有任何問題歡迎留言,wx搜索:python隨身聽,【在看】一下,下期見。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章