I am trying to sort a dictionary with respect to the keys. eg:
a = {3:2, 2:1, 1:6, 6:5}
I want to convert it to this without importing any package:
a = {1:6, 2:1, 3:2, 6:5}
I am trying to sort a dictionary with respect to the keys. eg:
a = {3:2, 2:1, 1:6, 6:5}
I want to convert it to this without importing any package:
a = {1:6, 2:1, 3:2, 6:5}
You can't really sort a dictionary by keys, but you can enumerate the dictionary by its keys sorted as seen below. Or you can manipulate the dict to a sorted OrderedDict as @Stef commented.
for key in sorted(a.keys()):
print(key,a[key])
See below (the solution is using OrderedDict which is part of core python and not an external package)
from collections import OrderedDict
a = {3:2,2:1,1:6,6:5}
b = {k:a[k] for k in sorted(a.keys())}
print(b)
outout
{1: 6, 2: 1, 3: 2, 6: 5}