Skip to content

Instantly share code, notes, and snippets.

@justinnaldzin
Last active April 27, 2018 02:25
Show Gist options
  • Save justinnaldzin/66b8b33970dcd570a006bcdaf517a024 to your computer and use it in GitHub Desktop.
Save justinnaldzin/66b8b33970dcd570a006bcdaf517a024 to your computer and use it in GitHub Desktop.
Recursively replace characters from keys of a Python dictionary
################################################################################
# The following demonstrates how to recursively replace specific characters
# from within keys of a nested dictionary or JSON object, leaving values as is.
################################################################################
# Given the following example dictionary with characters needing to be replaced:
example = [
{
"_id": "5ae2821988fc6a16af73aeb0",
"index": 0,
"keys_with_invalid_characters": [
{
"\tFour\t\tTabs\t": "\t\t\t\t",
"C,o,m,m,a,s": ",,,,",
"C{u}r{l}y{B}r{a}c{k}e{t}s": "{}{}",
"New\nLine\ns": "\n\n\n\n",
"P(a)r(e)n(t)h(e)s(e)s": "()()",
"S p a c e s": " ",
"S;e;m;i;c;o;l;o;n;s": ";;;;"
}
]
}
]
# Recursive function
def replace_keys(obj, old, new):
if isinstance(obj, dict):
return {k.replace(old, new): replace_keys(v, old, new) for k, v in obj.items()}
elif isinstance(obj, list):
return [replace_keys(i, old, new) for i in obj]
else:
return obj
# Replace invalid characters within keys with empty string
invalid_characters = ' ,;{}()\n\t='
for char in invalid_characters:
example = replace_keys(example, char, '')
# Results
import json
print(json.dumps(example, indent=4, sort_keys=True))
[
{
"_id": "5ae2821988fc6a16af73aeb0",
"index": 0,
"keys_with_invalid_characters": [
{
"Commas": ",,,,",
"CurlyBrackets": "{}{}",
"FourTabs": "\t\t\t\t",
"NewLines": "\n\n\n\n",
"Parentheses": "()()",
"Semicolons": ";;;;",
"Spaces": " "
}
]
}
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment