Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in Python by (47.6k points)

What would be a nice way to go from {2:3, 1:89, 4:5, 3:0} to {1:89, 2:3, 3:0, 4:5}?

I checked some posts but they all use the "sorted" operator that returns tuples.

1 Answer

0 votes
by (106k points)
edited by

First thing first the Standard Python dictionaries are unordered. So, even if you sorted the (key, value) pairs, you wouldn't be able to store them in a dict in a way that would preserve the ordering.

So,  the easiest way of sorting a dictionary by key is to use OrderedDict, which remembers the order in which the elements have been inserted:

The following example illustrates how we will use the ordered dictionary:-

import collections

d = {2:3, 1:89, 4:5, 3:0} 

od = collections.OrderedDict(sorted(d.items())) 

od 

image

To know more about this you can have a look at the following video tutorial:-

Related questions

Browse Categories

...