gpt4 book ai didi

python - 如果有重复的键,python 字典理解总是 "last wins"

转载 作者:太空狗 更新时间:2023-10-29 20:16:38 25 4
gpt4 key购买 nike

如果我创建一个带有字典理解的 python 字典,但有重复的键,我能保证最后一项将是最终字典中的那个吗?我看不清楚 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 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.

该文档还明确指出最后一项适用于逗号分隔的键值对 ({1: 1, 1: 2}) 和字典解包 ({** {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.

请注意 as wim points out ,如果存在相同但不同的 key ,则 key 的第一个版本获胜:

>>> {k: v for k, v in [(1, 1), (1.0, 2.0)]}
{1: 2.0}

在这里,最终的字典具有来自 (1, 1) 的键,但具有来自 (1.0, 2.0) 的值。

关于python - 如果有重复的键,python 字典理解总是 "last wins",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39678672/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com