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

Bengt Richter bokr at oz.net
Thu Oct 27 22:31:03 EDT 2005


On Thu, 27 Oct 2005 16:46:32 -0400, Mike Meyer <mwm at mired.org> wrote:

>"dcrespo" <dcrespo at gmail.com> writes:
>
>> Hi all,
>>
>> How can I replace all None values with the string 'Null' in a
>> dictionary?
>
>Iterate over everything in the dictionary:
>
>for key, item in mydict.items():
>    if item is None:
>       mydict[key] = 'Null'
>
Which is probably more efficient than one-liner updating the dict with

    mydict.update((k,'Null') for k,v in mydict.items() if v is None)

as in

 >>> mydict = dict(a=1, b=None, c=3, d=None, e=5)
 >>> mydict
 {'a': 1, 'c': 3, 'b': None, 'e': 5, 'd': None}
 >>> mydict.update((k,'Null') for k,v in mydict.items() if v is None)
 >>> mydict
 {'a': 1, 'c': 3, 'b': 'Null', 'e': 5, 'd': 'Null'}
 
(too lazy to measure ;-)

Regards,
Bengt Richter



More information about the Python-list mailing list