RE: How to update dictionary values while iterating in Python?

  • 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()}

Be the first to post a comment.

Add a comment