Last active
October 4, 2024 08:46
-
-
Save msenol86/9599512159fc99077075f65f1156099e to your computer and use it in GitHub Desktop.
Sort Dict (JSON)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.