假设我创建了一个字典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 dict显示最初是以这种方式设计的……可能没有人知道.
我们知道什么时候做出决定. Python 0.9.x(1991-1993)没有dict显示; 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 (te