Is there a pythonic shortcut to:
Code:if some_value is not None: my_dict['key'] = some_value
Is there a pythonic shortcut to:
Code:if some_value is not None: my_dict['key'] = some_value
- Micah Carrick | www.micahcarrick.com | GTK+ Forums
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.
- Micah Carrick | www.micahcarrick.com | GTK+ Forums
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.)
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?
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.But what is the problem with using the if statement?
I thought this may be one of those situations. Perhaps not.
Thanks everybody.
- Micah Carrick | www.micahcarrick.com | GTK+ Forums
Something like http://docs.python.org/library/stdty...ict.setdefault?
Last edited by navneeth; November 15th, 2010 at 08:27 PM.
surely [if some_value is not None:] is the same as [if some_value:]
Catch me on Freenode - imark
I don't see the reason why you'd want a shortcut for that...
If you want to assign a string in place of an empty string you can do code like:
This is a forced assignment unlike the code in your example which is why you need the if statement.Code:dict[key] = input or default_string
Bookmarks