Python3.9中的字典合併和更新,瞭解一下

全文共2837字,預計學習時長

9分鐘


Python3.9中的字典合併和更新,瞭解一下


Python3.9正在積極開發,並計劃於今年10月發佈。


2月26日,開發團隊發佈了alpha 4版本。該版本引入了新的合併(|)和更新(|=)運算符,這個新特性幾乎影響了所有Python程序員。


我們廢話少說,下面來點乾貨才是正事。


字典


字典,通常稱為dict,是Python中最重要的內置數據類型之一。這種數據類型是大小靈活的鍵值對集合,並且由於它哈希實現,它以具有恆定的數據查找時間而聞名。


以下是一些常見用法:


<code># Declare a dict
student = {'name': 'John', 'age': 14}# Get a value
age = student['age']
# age is 14# Update a value
student['age'] = 15
# student becomes {'name': 'John', 'age': 15}# Insert a key-value pair
student['score'] = 'A'
# student becomes {'name': 'John', 'age': 15, 'score': 'A'}/<code>


合併字典——舊方法


有時,兩個字典需要被合併來做進一步的處理。在3.9版本正式發佈之前,有幾種方法可以做到這一點。假設有兩個dict:d1和d2。我們想要創建一個新的dict:d3,它是d1和d2的集合。如果合併的dict之間有一些重疊的鍵,為了說明應該做什麼,引入另一個dict,d2a,它有一個與d1重疊的鍵。


<code># two dicts to start with
d1 = {'a': 1, 'b': 2}
d2 = {'c': 3, 'd': 4}
d2a = {'a': 10, 'c': 3, 'd': 4}# target dict
d3 = {'a': 1, 'b': 2, 'c': 3, 'd': 4}/<code>


使用update() 方法


Python3.9中的字典合併和更新,瞭解一下


第一種方法是使用dict的方法update()。下面的代碼片段展示瞭如何做到這一點。請注意,必須首先創建一個d1的副本,因為update() 函數將修改原始的dict。


<code># create a copy of d1, as update()modifies the dict in-place
d3 = d1.copy()
# d3 is {'a': 1, 'b': 2}# update the d3 with d2
d3.update(d2)
# d3 now is {'a': 1, 'b': 2, 'c': 3, 'd': 4}/<code>


當有重疊的鍵時,必須更加謹慎地選擇保留哪些值。正如在下面看到的,在update() 方法中作為參數傳遞的dict將通過重疊鍵(例如‘a’)的值(如10)來“贏得”遊戲。


<code>d3 = d1.copy()
d3.update(d2a)
# d3 now is {'a': 10, 'b': 2, 'c': 3, 'd': 4}
# This is not the way that we wantd3 = d2a.copy()
d3.update(d1)
# d3 now is {'a': 1, 'c': 3, 'd': 4, 'b': 2}
# This is the way that we want/<code>


打開字典


第二種方法是使用字典的打開。與上述方法類似,當有重疊的鍵時,“最後出現”的獲勝。


<code># unpacking
d3 = {**d1, **d2}
# d3 is {'a': 10, 'b': 2, 'c': 3, 'd': 4}
# Not rightd3 = {**d2a, **d1}
# d3 is {'a': 1, 'c': 3, 'd': 4, 'b': 2}
# Good/<code>


使用Dict(iterable, **kwarg)


在Python中創建字典的一種方法是使用 dict(iterable, **kwarg)類函數。與當前主題特別相關的是,當iterable是一個dict,將使用相同的鍵值對創建一個新的dict。至於關鍵字參數,可以傳遞另一個dict,這樣它將會將鍵值對添加到將要創建的dict中。請注意,這個關鍵字參數dict將用相同的鍵替換該值,類似於“最後出現”的獲勝。請看下面的例子。


<code>d3 = dict(d1, **d2)
# d3 is {'a': 1, 'b': 2, 'c': 3, 'd': 4}
# Good, it's what we wantd3 = dict(d1, **d2a)
# d3 is {'a': 10, 'b': 2, 'c': 3, 'd': 4}
# Not right, 'a' value got replaced/<code>


需要注意的是,只有當關鍵字參數dict以字符串作為關鍵字時,該方法才有效。如下所示,使用 int 作為關鍵字的dict是行不通的。


<code>>>> dict({'a': 1}, **{2:3})
Traceback (most recent call last):
 File "<stdin>", line 1,in <module>
TypeError: keywords must be strings
>>> dict({'a': 1}, **{'2': 3})
{'a': 1, '2': 3}/<module>/<stdin>/<code>


合併字典——新功能


Python3.9中的字典合併和更新,瞭解一下


在最新發布的Python 3.9.0a4中,可以非常方便地使用合併運算符|來合併兩個dict。下面給出了一個例子。你可能已經注意到,當這兩個dict之間有重疊的鍵時,最後出現的會留下,這種行為與上面看到的一致,比如update() 方法。


<code># use the merging operator |
d3 = d1 | d2
# d3 is now {'a': 1, 'b': 2, 'c': 3, 'd': 4}
# goodd3 = d1 | d2a
# d3 is now {'a': 10, 'b': 2, 'c': 3, 'd': 4}
# not good/<code>


與這個合併操作符相關的是在環境中操作的參數賦值版本(例如更新左側的dict)。本質上,它的功能與update()方法相同。下面的代碼片段展示了它的用法:


<code># Create a copy for d1
d3 = d1.copy()# Use the augmented assignment of the merge operator
d3 |= d2
# d3 now is {'a': 1, 'b': 2, 'c': 3, 'd': 4}
# goodd3 |= d2a
# d3 now is {'a': 10, 'b': 2, 'c': 3, 'd': 4}
# not good/<code>


在今天的文章裡,我們回顧了Python3.9中合併和更新字典的新特性。在幾個模塊中還有新的更新和改進,例如asyncio, math和os模塊。


期待當它正式發佈時,能發現更多驚喜,你準備好了嗎?


Python3.9中的字典合併和更新,瞭解一下

我們一起分享AI學習與發展的乾貨


分享到:


相關文章: