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': '[email protected]', 'Subscribed': None}],
'FriendCount': [{'SumAsString': 'xndiofa!#$*9'}]
}
Expected result:
{
'Location': [{
'Country': 'Japan',
}],
'PhoneNumber': [{'Number': '123-456-7890', 'PreferredLanguage': None}],
'EmailAddress': [{'Email': '[email protected]', '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
2
Answers
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.With single dict comprehension implying recursive calls: