DEV Community

Lam Nguyen
Lam Nguyen

Posted on

Answer: How can I sort a dictionary by key?

For CPython/PyPy 3.6, and any Python 3.7 or higher, this is easily done with:

>>> d = {2:3, 1:89, 4:5, 3:0}
>>> dict(sorted(d.items()))
{1: 89, 2: 3, 3: 0, 4: 5}

Top comments (0)