分配python字典文字:保证语义吗? [英] Assigning python dictionary literals: are the semantics guaranteed?

查看:69
本文介绍了分配python字典文字:保证语义吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个简单的问题:

Python 2.6.6 (r266:84292, Aug 9 2016, 06:11:56)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-17)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> d = {'foo':1,'foo':2}
>>> print d
{'foo': 2}
>>> d = {'foo':2,'foo':1}
>>> print d
{'foo': 1}

因此,似乎如果我将具有重复键的字典文字分配给变量,则至少是针对此特定的python版本,它是第二个键/对.

So it seems that if I assign a dictionary literal with a duplicate key to a variable it is the second key/pair that is used, at least for this particular python version.

这种行为能得到保证吗?

Is this behaviour guaranteed?

推荐答案

来自

如果给出了逗号分隔的键/基准对序列,则从左到右对其进行评估以定义词典的条目:每个键对象都用作词典中的键存储相应的基准. 这意味着您可以在键/基准列表中多次指定相同的键,并且该键的最终字典值将是最后一个给出的键.

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.

(加粗强调).

是的,这是可以保证的.所有Python实现都必须遵守这一点,与上述规范的差异将是一个错误.

So yes, that is guaranteed. All Python implementations must adhere to this, deviation from the above specification would be a bug.

较旧的Python版本文档并不一定总是包含最后一句话,但是评估的顺序始终是明确的.

Older Python version documentation have not always included that last sentence, but the order of evaluation has always been explicit.

这篇关于分配python字典文字:保证语义吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆