How to update dictionary values while iterating in Python?

Fredrick
Updated on February 18, 2026 in

 

I’m working with a Python dictionary and need to replace all None values with an empty string "".

For example:

mydict = {
    "name": "Alice",
    "age": None,
    "city": "New York",
    "email": None
}

I started with:

for k, v in mydict.items():
    if v is None:
        # update value here?

What’s the correct and cleanest way to modify the dictionary in place while iterating?

Is it safe to update values directly inside the loop, or is there a more Pythonic approach (e.g., dictionary comprehension)?

Would appreciate best-practice suggestions.

  • 1
  • 95
  • 2 months ago
 
on February 23, 2026
  • Modify the existing dictionary

mydict = {“name”: “Alice”, “age”: None, “city”: “New York”, “email”: None}

for k, v in mydict.items():

          if v is None:

                    mydict[k] = “”

 

  • Create a new dictionary

mydict = {k: (“” if v is None else v) for k, v in mydict.items()}

  • Liked by
Reply
Cancel
Loading more replies