問題描述
如果我創建一個帶有 dict 理解的 python 字典,但有重復的鍵,我是否保證最后一項將是最終字典中的那個?我看不清楚 https://www.python.org/dev/peps/pep-0274/?
If I create a python dictionary with a dict comprehension, but there are duplicate keys, am I guaranteed that the last item will be the one that ends up in the final dictionary? It's not clear to me from looking at https://www.python.org/dev/peps/pep-0274/?
new_dict = {k:v for k,v in [(1,100),(2,200),(3,300),(1,111)]}
new_dict[1] #is this guaranteed to be 111, rather than 100?
推薦答案
鍵的最后一個值獲勝.我能找到的最好的文檔在 Python 3 語言參考部分6.2.7:
The last value for a key wins. The best documentation I can find for this is in the Python 3 language reference, section 6.2.7:
與列表和集合推導相比,字典推導需要兩個用冒號隔開的表達式,后跟通常的for"和if"子句.運行推導時,生成的鍵和值元素按照它們產生的順序插入到新字典中.
A dict comprehension, in contrast to list and set comprehensions, needs two expressions separated with a colon followed by the usual "for" and "if" clauses. When the comprehension is run, the resulting key and value elements are inserted in the new dictionary in the order they are produced.
該文檔還明確指出,最后一項對于逗號分隔的鍵值對({1: 1, 1: 2}
)和字典解包({**{1:1},**{1:2}}
):
That documentation also explicitly states that the last item wins for comma-separated key-value pairs ({1: 1, 1: 2}
) and for dictionary unpacking ({**{1: 1}, **{1: 2}}
):
如果給出了以逗號分隔的鍵/數據對序列,...您可以在鍵/數據列表中多次指定同一個鍵,并且該鍵的最終字典值將是最后一個給出的值.
If a comma-separated sequence of key/datum pairs is given, ... you can specify the same key multiple times in the key/datum list, and the final dictionary’s value for that key will be the last one given.
雙星號**
表示字典解包.它的操作數必須是一個映射.每個映射項都添加到新字典中.以后的值替換已由較早的鍵/數據對和較早的字典解包設置的值.
A double asterisk **
denotes dictionary unpacking. Its operand must be a mapping. Each mapping item is added to the new dictionary. Later values replace values already set by earlier key/datum pairs and earlier dictionary unpackings.
請注意,wim 指出,如果有相同但不同的鍵,則鍵的第一個版本獲勝:
Note that as wim points out, the first version of a key wins if there are equal but distinct keys:
>>> {k: v for k, v in [(1, 1), (1.0, 2.0)]}
{1: 2.0}
這里,最終的 dict 的鍵來自 (1, 1)
,但值來自 (1.0, 2.0)
.
Here, the final dict has the key from (1, 1)
, but the value from (1.0, 2.0)
.
這篇關于python dict理解總是“最后贏"嗎?如果有重復的鍵的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!