How to update dictionary values while iterating in Python?

Fredrick
Updated 11 hours ago 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.

  • 0
  • 8
  • 11 hours ago
 
Loading more replies