On Thu, 5 Sep 2019 at 11:19, <r...@hwyl.org> wrote: > I find a common requirement I have is to include one or more entries in a > dict only if some condition is met. Currently, the usual way of doing that is > to add one or more if statements. > > Simple (but hopefully relatable-to-real-world-code) example. [...] > This is a fairly common (tedious) pattern in my code, but I feel it could be > avoided. In my view it would be better if it was possible to conditionally > add the entry in the dict declaration. > > My proposal is that there should be a special value defined that results in a > dict entry not being added to the dict if either the key or the value equals > this value. There may be several ways to achieve this, but here's one way it > could work.
This is pretty easy to write as a helper function: >>> def dct(**kw): ... return {k:v for k, v in kw.items() if v is not dct.skip} ... >>> dct.skip = object() >>> >>> dct(a=12, b=None, c=dct.skip, d="Hello", e=dct.skip) {'a': 12, 'b': None, 'd': 'Hello'} Given this, I'm not sure it's a sufficiently useful improvement to be worth adding to the builtin dictionary (although thanks for the suggestion, I wouldn't have ever thought about writing a helper to avoid the boilerplate without this posting to prompt me!) Paul _______________________________________________ Python-ideas mailing list -- python-ideas@python.org To unsubscribe send an email to python-ideas-le...@python.org https://mail.python.org/mailman3/lists/python-ideas.python.org/ Message archived at https://mail.python.org/archives/list/python-ideas@python.org/message/4B2LALDNOUN2AII7OPZM4TUURJHFF6NO/ Code of Conduct: http://python.org/psf/codeofconduct/