Is a python dict comprehension always “last wins” if there are duplicate keys

送分小仙女□ 提交于 2019-11-28 13:26:55

Last item 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.

If you mean something like

{key: val for (key, val) in pairs}

where pairs is an ordered collection (eg, list or tuple) of 2-element lists or tuples then yes, the comprehension will take the collection in order and the last value will "win".

Note that if pairs is a set of pairs, then there is no "last item", so the outcome is not predictable. EXAMPLE:

>>> n = 10
>>> pairs = [("a", i) for i in range(n)]
>>> {key:val for (key, val) in pairs}
{'a': 9}
>>> {key:val for (key, val) in set(pairs)}
{'a': 2}

am I guaranteed that the last item will the the one that ends up in the final dictionary?

Not exactly...

In case of duplicate keys, the first key is preserved, and the last value is preserved. The resulting item (key, value) may not have been present in any of the original pairs in the first place.

>>> {1.: 1, 1: 1.}
{1.0: 1.0}

This behaviour somewhat documented under Dictionary displays (emphasis mine):

This means that 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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!