Search code examples
pythondictionary-comprehension

Python - Replace None with empty string in Nested Dictionary


I want to replace None with empty string in Nested Dictionary.

test={
  "order":1234,
  "status":"delivered",
   "items":[
        {
          "name":"sample1",
          "code":"ASU123",
          "unit":None
      } ],
   "product":{"name":None,"code":None}
  }

I want to replace None with an empty string and store conversion of the dictionary into another variable like test1.

The following code is not allowing me to store it in another variable.

def replace_none(test_dict): 
  
    # checking for dictionary and replacing if None 
    if isinstance(test_dict, dict): 
        
        for key in test_dict: 
            if test_dict[key] is None: 
                test_dict[key] = '' 
            else: 
                replace_none(test_dict[key]) 
  
    # checking for list, and testing for each value 
    elif isinstance(test_dict, list): 
        for val in test_dict: 
            replace_none(val) 
   

Solution

  • as @Pranav Hosangadi mentioned, you can deep-copy test at first and then perform your function on the copied dict:

    import copy
    b = copy.deepcopy(test)
    replace_none(b)
    print(test)
    print(b)
    

    output:

    {'order': 1234, 'status': 'delivered', 'items': [{'name': 'sample1', 'code': 'ASU123', 'unit': None}], 'product': {'name': None, 'code': None}}
    {'order': 1234, 'status': 'delivered', 'items': [{'name': 'sample1', 'code': 'ASU123', 'unit': ''}], 'product': {'name': '', 'code': ''}}