I have a dictionary d
that I'd like to copy shallowly and then change some of its contents. 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?
CodePudding user response:
Quoting the section on dictionary displays in the Python language spec (my italics):
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.
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.
CodePudding user response:
From Python 3.6 onwards, the standard dict type maintains insertion order by default.
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
.
So yes! You can be sure that d[1]
gets overwritten by the updated value.