包含重复键的dict文字是否定义明确? [英] Is a dict literal containing repeated keys well-defined?

查看:51
本文介绍了包含重复键的dict文字是否定义明确?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我编写 d = {0:1、0:2} ,Python是否保证 d [0] 的值,还是未定义行为"??

If I write d = {0: 1, 0: 2}, does Python guarantee the value of d[0], or is it "undefined behavior"?

(当然,这不是您在编程时永远不会写的东西,但是这个问题主要是出于好奇.在本地,它似乎总是保存与键的最后一个键相关联的值发生,例如此处为 2 .不过,对于某些奇怪的代码生成情况,它可能是有用的信息.)

(Of course, this isn't something you'd ever write when programming, but this question is mostly out of curiosity. Locally, it seems to always save the value associated with the key's last occurrence, i.e. 2 here. Maybe it's useful info for some weird code gen situations, though.)

推荐答案

是的,它的定义很明确-最后一个值获胜. {0:1,0:2} 字典显示:

yes, it is well-defined -- last value wins. {0: 1, 0: 2} is a dictionary display:

如果给出了逗号分隔的键/基准对序列,则它们是从左到右评估 以定义字典的条目:每个键对象都用作字典中的键来存储相应的基准.这意味着您可以指定相同的密钥在键/基准列表中多次输入,然后最终词典的值因为该键将是给定的最后一个键.重点是我的

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.emphasis is mine

这篇关于包含重复键的dict文字是否定义明确?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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