Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python nested dictionary – remove "" and data with extra spaces but keep None values

I have a dictionary and would like to keep None values but remove values with "" and also values of any combination of " "’s

I have the following dictionary:

{'UserName': '',
 'Location': [{'City': '',
   'Country': 'Japan',
   'Address 1': '    ',
   'Address 2': ' '}],
 'PhoneNumber': [{'Number': '123-456-7890', 'ContactTimes': '', 'PreferredLanguage': None}],
 'EmailAddress': [{'Email': 'test@test.com', 'Subscribed': None}],
 'FriendCount': [{'SumAsString': 'xndiofa!#$*9'}]
}

Expected result:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{
 'Location': [{
   'Country': 'Japan',
}],
 'PhoneNumber': [{'Number': '123-456-7890', 'PreferredLanguage': None}],
 'EmailAddress': [{'Email': 'test@test.com', 'Subscribed': None}],
 'FriendCount': [{'SumAsString': 'xndiofa!#$*9'}]
}

I have this function and its partially working but I cant figure out how to remove key’s with the extra spaces.

def delete_junk(_dict):

    for key, value in list(_dict.items()):
        if isinstance(value, dict):
            delete_junk(value)
        elif value == '':
            del _dict[key]
        elif isinstance(value, list):
            for v_i in value:
                if isinstance(v_i, dict):
                    delete_junk(v_i)

    return _dict

>Solution :

Your approach was sound; I also think defining a function using recursion is how I would approach the problem. I would use .isspace() to help.

def delete_junk(d):
    """
    Recursively removes empty strings or strings consisting only of whitespaces
    from the input dictionary and its nested dictionaries and lists.
    """
    if isinstance(d, dict):
        return {k: remove_empty_strings(v) for k, v in d.items() if v != "" and not str(v).isspace()}
    elif isinstance(d, list):
        return [remove_empty_strings(v) for v in d if v != "" and not str(v).isspace()]
    else:
        return d


i = {'UserName': '',
 'Location': [{'City': '',
   'Country': 'Japan',
   'Address 1': '    ',
   'Address 2': ' '}],
 'PhoneNumber': [{'Number': '123-456-7890', 'ContactTimes': '', 'PreferredLanguage': None}],
 'EmailAddress': [{'Email': 'test@test.com', 'Subscribed': None}],
 'FriendCount': [{'SumAsString': 'xndiofa!#$*9'}]
}

output_dict = delete_junk(i)

print(output_dict)
# Output: {'Location': [{'Country': 'Japan'}],
#          'PhoneNumber': [{'Number': '123-456-7890', 'PreferredLanguage': None}],
#          'EmailAddress': [{'Email': 'test@test.com', 'Subscribed': None}],
#          'FriendCount': [{'SumAsString': 'xndiofa!#$*9'}]}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading