Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Some nested dictionaries in Python, say from a XML have https entries in many tags. this method cleans them up.
def deep_clean(element, damn): # the values have the annoying {http} field this removes them.
try:
if isinstance(element, dict):
return {k.replace(damn, '').replace('@', '').replace('#', ''): deep_clean(element[k], damn) for k in
element}
elif isinstance(element, list):
return [deep_clean(e, damn) for e in element]
elif isinstance(element, str):
if re.fullmatch('\d*', element):
return int(element)
elif re.fullmatch('-?\+?\d*\.?\d*e?\d*', element):
return float(element)
else:
return element.replace(damn, '') # there should not be a damn
else:
return element
except ValueError:
return element
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.