python - 为什么 `dict_display` 允许重复键?

标签 python dictionary

我的意思不是因为标准这么说,而是它的基本原理。规范说:

If a comma-separated sequence of key/datum pairs is given, they 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. This means that 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.

这意味着通过以下方式形成 dict 是完全合法的:

d = { 'a': 1, 'b':2, 'b':3 }

然而,我几乎看不出有任何人愿意这样定义它的原因,我通常认为这是一个错误。如果将关键字参数与函数进行比较,则禁止相应的构造。

有什么好的方法可以避免这种情况吗?

最佳答案

此“错误”已被报告、讨论并最终被拒绝 - 参见 https://bugs.python.org/issue16385 .

拒绝者指出的主要原因是

A code generator could depend on being able to write duplicate keys without having to go back and erase previous output.

还有那个

An error is out of the question for compatibility reasons.

关于python - 为什么 `dict_display` 允许重复键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41802298/

相关文章:

python - Flask migrate 未检测到列自动增量更改?

python - 如何在 pandas 中按列名称连接列?

C++ - STL - 映射到 int 表

python - 添加不同字典的键值并将其存储在另一个字典中

与 SQLAlchemy 一起使用的 Python 框架

python - 尽管调用 set_expiry(0),Django session 仍会过期

python - scikit-learn:通过随机采样填充缺失值

python - appengine 图像 api 错误

python:对有序字典进行排序

python - 访问 Pandas 系列的索引