How to replace all None values with the string "Null" in a dictionary

Steven D'Aprano steve at REMOVETHIScyber.com.au
Fri Oct 28 19:25:36 EDT 2005


On Fri, 28 Oct 2005 05:23:00 -0700, dcrespo wrote:

>> I think it would be time for you to read the Fine Manual...
> 
> hi, thanks for your answer... I really did it the same way you
> suggested, but I forgot to tell you that I wanted to get a better way
> for doing it.

What was wrong with the way you used?

Was it too easy to understand? Not difficult enough? Too few bugs?

You could try something like this:

def substitute(D):
    L = D.keys()[:]
    i = 0
    while (i < len(L)) is True:
        key = L[i]
        if D[key] == None:
            D[key] = 'Null'
        else:
            del L[i]
        i = i + 1
    return D


D = {'item1': None, 'item2': 23, 'item3': 42, 'item4': None, 'item5': 15}

print substitute(D) 

gives {'item1': 'Null', 'item2': 23, 'item3': 42, 'item4': 'Null',
'item5': 15} as needed.

And I really, really hope this is of no hope whatsoever! ;-)



-- 
Steven




More information about the Python-list mailing list