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:
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.
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.
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}
Here, the final dict has the key from (1, 1)
, but the value from (1.0, 2.0)
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…