Skip to content

Instantly share code, notes, and snippets.

@msenol86
Last active October 4, 2024 08:46
Show Gist options
  • Select an option

  • Save msenol86/9599512159fc99077075f65f1156099e to your computer and use it in GitHub Desktop.

Select an option

Save msenol86/9599512159fc99077075f65f1156099e to your computer and use it in GitHub Desktop.
Sort Dict (JSON)
import json
JSON_VALUE = list | dict | str | int | float
def rec_sort(dict_or_list_or_value: JSON_VALUE) -> JSON_VALUE:
if type(dict_or_list_or_value) is dict:
ret_dict = {}
for k in sorted(dict_or_list_or_value.keys()):
ret_dict[k] = rec_sort(dict_or_list_or_value[k])
return ret_dict
elif type(dict_or_list_or_value) is list:
ret_list = []
for x in dict_or_list_or_value:
if type(x) is dict:
ret_list.append(json.dumps(rec_sort(x), sort_keys=True))
elif type(x) is list:
ret_list.append(json.dumps(rec_sort(x), sort_keys=True))
else:
ret_list.append(json.dumps(x, sort_keys=True))
ret_list = sorted(ret_list)
return [json.loads(x) for x in ret_list]
else:
return dict_or_list_or_value
@msenol86
Copy link
Author

msenol86 commented Oct 4, 2024

When comparing two dictionaries, if the item order in a nested list element is different than the other dictionary, Python considers these two dictionaries as not being equal. This algorithm sorts all nested elements (lists or dictionaries) in the dictionary, which is not possible in standard Python, and solves the issue with nested lists that have a different order.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment