0 votes
1 view
in Python by (47.8k 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 (107k 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())) 



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

Related questions

0 votes
1 answer
asked Aug 23, 2019 in Python by Sammy (47.8k points)
+1 vote
1 answer
0 votes
1 answer
asked Jul 3, 2019 in Python by Sammy (47.8k points)
0 votes
1 answer
Welcome to Intellipaat Community. Get your technical queries answered by top developers !