0

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}
fcdt
  • 2,371
  • 5
  • 14
  • 26
Raj Tiwari
  • 13
  • 5
  • 2
    Does this answer your question? [How can I sort a dictionary by key?](https://stackoverflow.com/questions/9001509/how-can-i-sort-a-dictionary-by-key) – Stef Oct 01 '20 at 10:04
  • if its python 3.7+ `ordered = dict(sorted(a.items()))` – GhandiFloss Oct 01 '20 at 10:11

2 Answers2

-1

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])
Goldwave
  • 599
  • 3
  • 13
  • That's not exactly what I said - I merely pointed out that the question was a duplicate. Since Python 3.7, `dict` have order. So you could just write `sorted_dict = dict(sorted(unsorted_dict.items()))`. – Stef Oct 01 '20 at 10:19
  • See also: [Are dictionaries ordered in Python 3.6+?](https://stackoverflow.com/questions/39980323/are-dictionaries-ordered-in-python-3-6) – Stef Oct 01 '20 at 10:24
-2

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}
balderman
  • 22,927
  • 7
  • 34
  • 52