From f02e959476df52a252b9a8c6711cd2fa755781f2 Mon Sep 17 00:00:00 2001 From: Isabelle Viktoria Maciohsek Date: Fri, 16 Oct 2020 21:24:33 +0300 Subject: [PATCH] Add sort_dict_by_key --- snippets/sort_dict_by_key.md | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 snippets/sort_dict_by_key.md diff --git a/snippets/sort_dict_by_key.md b/snippets/sort_dict_by_key.md new file mode 100644 index 000000000..8d7fcc5c5 --- /dev/null +++ b/snippets/sort_dict_by_key.md @@ -0,0 +1,21 @@ +--- +title: sort_dict_by_key +tags: dictionary,intermediate +--- + +Sorts the given dictionary by key. + +- Use `dict.items()` to get a list of tuple pairs from `d` and sort it using `sorted()`. +- Use `dict()` to convert the sorted list back to a dictionary. +- Use the `reverse` parameter in `sorted()` to sort the dictionary in reverse order, based on the second argument. + +```py +def sort_dict_by_key(d, reverse = False): + return dict(sorted(d.items(), reverse = reverse)) +``` + +```py +d = {'one': 1, 'three': 3, 'five': 5, 'two': 2, 'four': 4} +sort_dict_by_key(d) # {'five': 5, 'four': 4, 'one': 1, 'three': 3, 'two': 2} +sort_dict_by_key(d, True) # {'two': 2, 'three': 3, 'one': 1, 'four': 4, 'five': 5} +```