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

时间:2023-02-04
本文介绍了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).

这篇关于python dict理解总是“最后赢"吗?如果有重复的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!

上一篇:根据每个子列表中的第三项删除列表列表中的重 下一篇:复制列表中的字符串并将整数后缀添加到新添加

相关文章

最新文章