gpt4 book ai didi

python - 当字典键相同时,为什么 Python 只保留最后一个键值对?

转载 作者:太空狗 更新时间:2023-10-30 02:24:44 26 4
gpt4 key购买 nike

假设我创建了一个字典 a_dictionary,其中两个键值对具有相同的键:

In [1]: a_dictionary = {'key': 5, 'another_key': 10, 'key': 50} 

In [2]: a_dictionary
Out[2]: {'key': 50, 'another_key': 10}

为什么 Python 在此处选择保留最后一个键值对而不是抛出有关使用相同键的错误(或至少发出警告)?

在我看来,这里的主要缺点是您可能会在不知不觉中丢失数据。

(如果相关,我在 Python 3.6.4 上运行了上面的代码。)

最佳答案

如果您的问题是为什么 Python 字典显示最初是这样设计的……可能没人知道。


我们知道何时做出决定。 Python 0.9.x (1991-1993) 没有字典显示; Python 1.0.x (1994) 做到了。他们的工作方式与今天完全一样。来自文档:1

A dictionary display yields a new dictionary object.

The key/datum pairs are evaluated from left to right to define the entries of the dictionary: each key object is used as a key into the dictionary to store the corresponding datum.

Restrictions on the types of the key values are listed earlier in section types.

Clashes between duplicate keys are not detected; the last datum (textually rightmost in the display) stored for a given key value prevails.

然后,测试它:

$ ./python
Python 1.0.1 (Aug 21 2018)
Copyright 1991-1994 Stichting Mathematisch Centrum, Amsterdam
>>> {'key': 1, 'other': 2, 'key': 3}
{'other': 2, 'key': 3}

但没有提及 Guido 为什么选择这种设计:

此外,如果您查看具有相似功能的不同语言,有些语言会像 Python 一样保留最后一个键值对,有些保留任意键值对,有些会引发某种错误……每种语言都足够了您不能说这是一个显而易见的设计,这就是 Guido 选择它的原因。


如果你想要一个可能并不比你自己猜的更好的疯狂猜测,这是我的:

编译器不仅可以,而且确实,通过创建一个空的字典并向其中插入键值对,有效地从文字中构造常量值。因此,默认情况下您会获得允许重复的、最后一个键获胜的语义;如果您还想要其他任何东西,则必须编写额外的代码。而且,由于没有令人信服的理由来选择一个而不是另一个,Guido 选择不编写额外的代码。


那么,如果设计没有令人信服的理由,为什么从那以后的 24 年里没有人试图改变它?

好吧,有人提出了一个功能请求 ( b.p.o. #16385 ),使重复键成为 3.4 中的一个错误。但当有人建议它在 -ideas 上提出时,它显然消失了。)它可能已经出现了几次,但显然没有人希望它改变得足够糟糕来插入它。

与此同时,他最接近 Python 现有行为的实际论据的是 Terry J. Reedy 的评论:

Without more use cases and support (from discussion on python-ideas), I think this should be rejected. Being able to re-write keys is fundamental to Python dicts and why they can be used for Python's mutable namespaces. A write-once or write-key-once dict would be something else.

As for literals, a code generator could depend on being able to write duplicate keys without having to go back and erase previous output.


<子>1。我不认为 1.0 的文档可以在任何地方直接链接,但您可以下载 the whole 1.0.1 source archive并从 TeX 源构建文档。

关于python - 当字典键相同时,为什么 Python 只保留最后一个键值对?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51951429/

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