PDA

View Full Version : Python shortcut for variable assignment if not None



MicahCarrick
November 15th, 2010, 03:07 PM
Is there a pythonic shortcut to:


if some_value is not None:
my_dict['key'] = some_value

MicahCarrick
November 15th, 2010, 03:08 PM
I should add that my_dict['key'] is not defined before. In other words,

my_dict['key'] = some_value or None

will not work because the key 'key' shouldn't even exist in the dictionary if some_value is none.

Arndt
November 15th, 2010, 03:25 PM
I should add that my_dict['key'] is not defined before. In other words,

my_dict['key'] = some_value or None

will not work because the key 'key' shouldn't even exist in the dictionary if some_value is none.

One question is whether you want an existing value to disappear in case some_value is None. Of course that's not what your code does, but sometimes it may be the proper thing to do.

(Not being a python expert, I dare not suggest that anything in particular is pythonic.)

ziekfiguur
November 15th, 2010, 06:53 PM
I can't really think of a shortcut to do that. Maybe you can remove the `is not None' part depending on the type some_value.
But what is the problem with using the if statement?

MicahCarrick
November 15th, 2010, 07:05 PM
But what is the problem with using the if statement?

Nothing. My background is in C and PHP so I often overlook some of the beauty of python (like list comprehension). I have to make a conscious effort to take a second look at my code looking for pythonic ways to refactor bits.

I thought this may be one of those situations. Perhaps not.

Thanks everybody.

navneeth
November 15th, 2010, 08:24 PM
Is there a pythonic shortcut to:


if some_value is not None:
my_dict['key'] = some_value



I should add that my_dict['key'] is not defined before. In other words,

my_dict['key'] = some_value or None

will not work because the key 'key' shouldn't even exist in the dictionary if some_value is none.

Something like http://docs.python.org/library/stdtypes.html#dict.setdefault?

CaptainMark
November 15th, 2010, 10:50 PM
surely [if some_value is not None:] is the same as [if some_value:]

Arndt
November 15th, 2010, 10:57 PM
surely [if some_value is not None:] is the same as [if some_value:]

some_value = 0

nvteighen
November 16th, 2010, 08:18 AM
I don't see the reason why you'd want a shortcut for that...

StephenF
November 16th, 2010, 12:28 PM
If you want to assign a string in place of an empty string you can do code like:


dict[key] = input or default_string
This is a forced assignment unlike the code in your example which is why you need the if statement.