[Python-ideas] PEP: Dict addition and subtraction
James Lu
jamtlu at gmail.com
Mon Mar 4 19:53:17 EST 2019
On Mar 4, 2019, at 11:25 AM, Steven D'Aprano <steve at pearwood.info> wrote:
>> How many situations would you need to make a copy of a dictionary and
>> then update that copy and override old keys from a new dictionary?
>>
>
> Very frequently.
>
> That's why we have a dict.update method, which if I remember correctly,
> was introduced in Python 1.5 because people were frequently re-inventing
> the same wheel:
>
> def update(d1, d2):
> for key in d2.keys():
> d1[key] in d2[key]
>
>
> You should have a look at how many times it is used in the standard
> library:
>
> [steve at ando cpython]$ cd Lib/
> [steve at ando Lib]$ grep -U "\.update[(]" *.py */*.py | wc -l
> 373
>
> Now some of those are false positives (docstrings, comments, non-dicts,
> etc) but that still leaves a lot of examples of wanting to override old
> keys. This is a very common need. Wanting an exception if the key
> already exists is, as far as I can tell, very rare.
It is very rare when you want to modify an existing dictionary. It’s not rare at all when you’re creating a new one.
>
> It is true that many of the examples in the std lib involve updating an
> existing dict, not creating a new one. But that's only to be expected:
> since Python didn't provide an obvious functional version of update,
> only an in-place version, naturally people get used to writing
> in-place code.
My question was “How many situations would you need to make a copy of a dictionary and then update that copy and override old keys from a new dictionary?” Try to really think about my question, instead of giving answering with half of it to dismiss my point.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20190304/a5b5bf9f/attachment.html>
More information about the Python-ideas
mailing list