python dict理解总是“最后赢"吗?如果有重复的键

问题描述

如果我创建一个带有 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).

相关文章