Is a python dict comprehension always quot;last winsquot; if there are duplicate keys(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理解总是“最后赢"吗?如果有重复的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:python dict理解总是“最后赢"吗?如果有重复的
基础教程推荐
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
