Python 嵌套字典 - 删除带有额外空格的" "和数据,但保留 None 值



我有一个字典,并希望保持None值,但删除值与"以及任意组合的值"‘s

我有以下字典:

{'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'}]
}

预期结果:

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

我有这个功能,它的部分工作,但我不知道如何删除键的额外空间。

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

你的方法是合理的;我也认为用递归定义一个函数是我解决这个问题的方法。我将使用.isspace()来帮助。

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'}]}

单字典推导意味着递归调用:

def delete_junk(d):
return {k: [delete_junk(i) for i in v] if isinstance(v, list) else v
for k, v in d.items() 
if not isinstance(v, str) or v.strip()}
print(delete_junk(dct))

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

相关内容

  • 没有找到相关文章

最新更新