Python 3 Sort Dict by Key

March 9, 2020
# {1: 'One', 3: 'Three', 2: 'Two'}
data = {
    1: 'One',
    3: 'Three',
    2: 'Two'
}

# {1: 'One', 2: 'Two', 3: 'Three'}
sorted_data = dict(sorted(data.items()))

# {3: 'Three', 2: 'Two', 1: 'One'}
reverse_data = dict(sorted(data.items(), reverse=True))
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.