views:

368

answers:

3

If the value is None, I'd like to change it to "" (empty string).

I start off like this, but I forget:

for k, v in mydict.items():
    if v is None:
... right?
+6  A: 
for k, v in mydict.iteritems():
    if v is None:
        mydict[k] = ''

In a more general case, e.g. if you were adding or removing keys, it might not be safe to change the structure of the container you're looping on -- so using items to loop on an independent list copy thereof might be prudent -- but assigning a different value at a given existing index does not incur any problem, so, in Python 2.any, it's better to use iteritems.

Alex Martelli
perhaps s/index/key/
John Machin
@John, it applies to _any_ built-in **container** -- just as much to a list as to a dict -- and I think "index" is a more generic term than "key".
Alex Martelli
A: 

Comprehensions are usually faster, and this has the advantage of not editing mydict during the iteration

mydict = dict([(k, v if v else "") for k,v in mydict.items()])
mountainswhim
If you are using `.items()` it doesn't matter (for python2) if you modify `mydict` as the list that `.items()` returns will not change even if you add/remove keys of `mydict`
gnibbler
Changing only values in a dict is never a problem; grief is caused by adding/deleting KEYS while iterating over the dict. Comprehensions are faster than WHAT? Really fast: copying the whole dict when there's one or two Nones to change. Speaking of Nones, you should have `if v is not None` instead of `if v` (re-read the question). Overall summary: -1
John Machin
+2  A: 
Paul McGuire