Sort dictionary by key

Python, Dictionary · Nov 2, 2020

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.
def sort_dict_by_key(d, reverse = False):
  return dict(sorted(d.items(), reverse = reverse))
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}

More like this

  • Sort dictionary by value

    Sorts the given dictionary by value.

    Python, Dictionary · Jan 7, 2021

  • Find keys with value

    Finds all keys in the provided dictionary that have the given value.

    Python, Dictionary · Nov 2, 2020

  • Find key of value

    Finds the first key in the provided dictionary that has the given value.

    Python, Dictionary · Nov 2, 2020