Skip to content

Instantly share code, notes, and snippets.

@hjwp
Last active December 19, 2015 17:28
Show Gist options
  • Save hjwp/5990967 to your computer and use it in GitHub Desktop.
Save hjwp/5990967 to your computer and use it in GitHub Desktop.
Fix Python dict repr so that they are alphabetically. currently handles 2-item dicts, probably very brittle
def fix_dict_repr_order(string):
dict_finder = r"({'\w+': .+, '\w+': .+})"
if not re.search(dict_finder, string):
return string
for dict_repr in re.findall(dict_finder, string):
items = re.search(
r"{('\w+': .+), ('\w+': .+)}",
dict_repr,
).groups()
string = string.replace(dict_repr, "{%s}" % (', '.join(sorted(items)),))
return string
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment