Skip to content

Instantly share code, notes, and snippets.

@jackylamhk
Last active November 7, 2023 16:58
Show Gist options
  • Save jackylamhk/eb85356f5740b328aa61fc323c35748d to your computer and use it in GitHub Desktop.
Save jackylamhk/eb85356f5740b328aa61fc323c35748d to your computer and use it in GitHub Desktop.
Sorting a big dict with recursion
def sort_dict(dictionary: dict) -> dict:
LIST_KEYS = ["priority", "clientId", "providerId", "clientScope", "alias", "name"]
def _get_list_sort_key(d: dict):
for key in LIST_KEYS:
if key in d:
return d[key]
return d[sorted(d.keys())[0]]
def _sort_dict(obj: any):
if isinstance(obj, dict):
return {k: _sort_dict(v) for k, v in sorted(obj.items())}
elif isinstance(obj, list):
if all(isinstance(e, (int, float, str)) for e in obj):
return sorted(obj)
else:
temp_list = [_sort_dict(e) for e in obj]
return sorted(temp_list, key=_get_list_sort_key)
else:
return obj
return _sort_dict(dictionary)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment