A more "pythonic" approach to "check for None and deal with it"

coding-style, python, string

Solution

If you are going to use sentinel values (None) then you will be burdened with checking for them.

There are a lot of different answers to your question, but they seem to be missing this point: don't use sentinel values in a dictionary when the absence of an entry encodes the same information.

For example:

bibliography = [
    { 'name': 'bdhar', 'summary': 'questioner' },
    { 'name': 'msw', 'content': 'an answer' },
]

then you can

for article in bibliography:
    for key in article:
        ...

and then your loop is nicely ignorant of what keys, if any, are contained in a given article.

In reading your comments, you claim that you are getting the dict from somewhere else. So clean it of junk values first. It is much more clear to have a cleaning step then it is to carry their misunderstanding through your code.

Problem

I have a `list` of `dict` with keys `['name','content','summary',...]`. All the values are strings. But some values are `None`. I need to remove all the new lines in `content`, `summary` and some other keys. So, I do this: ``` ... ... for item in item_list: name = item['name'] content = item['content'] if content is not None: content = content.replace('\n','') summary = item['summary'] if summary is not None: summary = summary.replace('\n','') ... ... ... ... ``` I somewhat feel that the `if x is not None: x = x.replace('\n','')` idiom not so intelligent or clean. Is there a more "pythonic" or better way to do it? Thanks.

Original source

Related problems