[Python-ideas] Syntax to conditionally define a field in a dict
Ned Batchelder
ned at nedbatchelder.com
Fri Apr 26 12:13:33 EDT 2019
On 4/26/19 11:03 AM, Joshua Marshall wrote:
> Hello all,
>
> I have a use case where I need to send a `dict` to a module as an
> argument. Inside of this, it has a multi-level structure, but each
> field I need to set may only be set to a single value. Fields must be
> valid, non-empty strings. It looks a lot like the following in my code:
>
> ```
> def my_func(val_1, val_2):
> return {
> "field_1": val_1,
> "next_depth": {
> "field_2": val_2
> }
> }
> ```
>
> What I want to do is:
> ```
> def my_func(val_1, val_2):
> return {
> "field_1": val_1 if val_1,
> "next_depth": {
> "field_2": val_2 if val_2
> }
> }
> ```
>
It's not clear in this example what you would want if val_2 is None.
Should it be:
{ "field_1": val_1 }
or:
{ "field_1": val_1, "next_depth": {} }
?
Better would be to build your dict with the tools you already have:
d = {}
if val_1:
d['field_1'] = val_1
if val_2:
d['next_depth'] = { 'field_2': val_2 }
You have total control over the results, and it doesn't take much more
space than your proposal.
Various helper function could make the code more compact, and even
clearer than your proposal:
d = {}
add_maybe(d, val_1, "field_1")
add_maybe(d, val_2, "next_depth", "field_2")
Of course, you might prefer a different API. That's an advantage of
helper functions: you can design them to suit your exact needs.
--Ned.
More information about the Python-ideas
mailing list