简体   繁体   English

Python:字典初始化的顺序

[英]Python: order of dictionary initialization

I have a dictionary d that I'd like to copy shallowly and then change some of its contents.我有一本字典d ,我想浅浅地复制它,然后更改它的一些内容。 I noticed that if I write the changed property first, it'll get overwritten.我注意到如果我先写改变的属性,它会被覆盖。 If I write it last, it persists:如果我最后写它,它仍然存在:

>>> d = {1: 1, 2: 2}
{1: 1, 2: 2}
>>> d1 = {1: 11, **d}
{1: 1, 2: 2}
>>> d2 = {**d, 1: 11}
{1: 11, 2: 2}

However, I know the order in a dictionary isn't reliable.但是,我知道字典中的顺序不可靠。 Can I assume that in {**d, 1: 11} , d[1] definitely gets overwritten by the updated value?我可以假设在{**d, 1: 11}中, d[1]肯定会被更新的值覆盖吗?

Quoting the section on dictionary displays in the Python language spec (my italics):引用Python 语言规范中的字典显示部分(我的斜体):

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.如果给出逗号分隔的键/数据对序列,则从左到右评估它们以定义字典的条目:每个键 object 用作字典中的键以存储相应的数据。 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.这意味着您可以在键/数据列表中多次指定同一个键,并且该键的最终字典值将是最后一个给定的值。

A double asterisk ** denotes dictionary unpacking.双星号 ** 表示字典解包。 Its operand must be a mapping.它的操作数必须是一个映射。 Each mapping item is added to the new dictionary.每个映射项都添加到新字典中。 Later values replace values already set by earlier key/datum pairs and earlier dictionary unpackings.以后的值替换已由较早的键/数据对和较早的字典解包设置的值。

Unless I'm missing something, this seems to guarantee that later values overwrite earlier ones.除非我遗漏了什么,否则这似乎可以保证后面的值会覆盖前面的值。

From Python 3.6 onwards, the standard dict type maintains insertion order by default.从 Python 3.6 开始,标准 dict 类型默认保持插入顺序。

In this case, later occurrences overwrite previous ones.在这种情况下,后面的事件会覆盖之前的事件。

So, if you say d1 = {1: 11, **d} , the value of the 1 would be updated with new value, and if you say d2 = {**d, 1: 11} , the value of 1 in d would be updated with 1: 11 .因此,如果您说d1 = {1: 11, **d} ,则1的值将更新为新值,如果您说d2 = {**d, 1: 11} ,则1的值在d将更新为1: 11

So yes!所以是的! You can be sure that d[1] gets overwritten by the updated value.您可以确定d[1]被更新的值覆盖。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM