-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Sort the final output for a deterministic order (#43)
* Sort the final output * Add fallback keys
- Loading branch information
Showing
2 changed files
with
34 additions
and
2 deletions.
There are no files selected for viewing
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
class Sort: | ||
@staticmethod | ||
def sort_nested(data, sort_keys=None): | ||
""" | ||
TODO: This is probably too generic and not the best way, but it works for now | ||
""" | ||
if sort_keys is None: | ||
sort_keys = ["start", "code", "title", "name"] | ||
|
||
def get_sort_key(item): | ||
return tuple(item.get(key, "") for key in sort_keys) | ||
|
||
if isinstance(data, dict): | ||
return { | ||
key: Sort.sort_nested(value, sort_keys) | ||
for key, value in sorted(data.items()) | ||
} | ||
elif isinstance(data, list): | ||
if all(isinstance(item, dict) for item in data): | ||
return sorted( | ||
(Sort.sort_nested(item, sort_keys) for item in data), | ||
key=get_sort_key, | ||
) | ||
else: | ||
return sorted(Sort.sort_nested(item, sort_keys) for item in data) | ||
else: | ||
return data |
This file contains 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