Updating Dictionary in Python 3.9
morioh.com
morioh.com
This page has a massive sidebar, another massive sidebar that scrolls with the content, and another sidebar. The content for my screen had about 1" width to read.
The various sidebars inexplicable start and stop scrolling as I scrolled down, meaning I got through 1/4 and closed the tab.
Atrocious and anti-user.
* First example, merge with update:
# d1 and d2 being dicts
d3 = d1.copy()
d3.update(**d2)
* Second example, using dict(): d3 = dict(d1, **d2)
* Third example (3.9 onwards): d3 = d1 | d2
# or
d3 = d1.copy()
d3 |= d2
The examples also show how each operation works (tl;dr: last value assigned to a key "wins").I might remember to try again on desktop where I can kill the element.
Dictionary Merge & Update Operators
Merge (|) and update (|=) operators have been added to the built-in dict class. See PEP 584 [2] for a full description. (Contributed by Brandt Bucher in bpo-36144 [3].)
[1]: https://docs.python.org/3.9/whatsnew/3.9.html "What’s New In Python 3.9"
[2]: https://www.python.org/dev/peps/pep-0584 "PEP 584"
[3]: https://bugs.python.org/issue36144 "bpo-36144"
Also, the ads in this website are terrible.
There should be one-- and preferably only one --obvious way to do it.
The key word, so often ignored, is OBVIOUS.Now, we can argue what "obvious" means, and what is more obvious to different people. But this one word makes a huge difference.
This change explicitly creates a situation where you have two equivalent obvious ways to do one thing, dict.update() and dict.|=, and is the latest in a string of such changes.
I personally _like_ this change, but python used to be much more conservative.
Plus, within the last few days, PEP 614 (Relaxing Grammar Restrictions On Decorators) [1] was also accepted for Python 3.9.
[0] https://docs.python.org/3.9/whatsnew/3.9.html [1] https://www.python.org/dev/peps/pep-0614/
“There is not too many ways to initialize and merge dicts in python. Let’s add one more!”
Which one is idiomatic now?
Imagine a large codebase where all these possible ways of doing one thing are inconsistent and misaligned. I remember myself replacing % string format notation with .format() everywhere. Just for the sake of consistency. And then they introduced one more way to format strings...
Note that the two new operators introduced for dict
a | b
a |= b
brings the behavior in line with the same operators for set. [1][1]: https://docs.python.org/3.8/library/stdtypes.html#set-types-...