Skip to content

Instantly share code, notes, and snippets.

@mikegrima
Created December 12, 2019 20:21
Show Gist options
  • Save mikegrima/684d8e14150cee1801aeba8e554fc003 to your computer and use it in GitHub Desktop.
Save mikegrima/684d8e14150cee1801aeba8e554fc003 to your computer and use it in GitHub Desktop.
Strip unicode from Python 2 Dictionary
# Strip out the unicode keys from a Python 2 dictionary (also includes nested Lists, Dicts, and Sets):
def py2_strip_unicode_keys(blob):
"""For Python 2 Only -- this will convert unicode keys in nested dictionaries to standard strings."""
if type(blob) == unicode:
return str(blob)
elif type(blob) == dict:
for key in list(blob.keys()):
value = blob.pop(key)
blob[str(key)] = py2_strip_unicode_keys(value)
elif type(blob) == list:
for i in range(0, len(blob)):
blob[i] = py2_strip_unicode_keys(blob[i])
elif type(blob) == set:
new_set = set()
for value in blob:
new_set.add(py2_strip_unicode_keys(value))
blob = new_set
return blob
bad_dict = {
u'some': u'value',
u'a': {
u'nested': [
u'List',
u'of',
{
u'unicode': u'values'
}
]
},
u'and a': {
u'nested',
u'set',
u'of',
5,
u'values'
}
}
value = py2_strip_unicode_keys(bad_dict)
# value will equal {'a': {'nested': ['List', 'of', {'unicode': 'values'}]}, 'some': 'value', 'and a': set(['of', 'set', 'values', 5, 'nested'])}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment