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.
To sort dictionary key in python we can use dict. items() and sorted(iterable) method. Dict. items() method returns an object that stores key-value pairs of dictionaries.
To sort a list of dictionaries according to the value of the specific key, specify the key parameter of the sort() method or the sorted() function. By specifying a function to be applied to each element of the list, it is sorted according to the result of that function.
To sort a dictionary by value in Python you can use the sorted() function. Python's sorted() function can be used to sort dictionaries by key, which allows for a custom sorting method. sorted() takes three arguments: object, key, and reverse. Dictionaries are unordered data structures.
Standard Python dictionaries are unordered (until Python 3.7). 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.
The easiest way is to use OrderedDict
, which remembers the order in which the elements have been inserted:
In [1]: import collections In [2]: d = {2:3, 1:89, 4:5, 3:0} In [3]: od = collections.OrderedDict(sorted(d.items())) In [4]: od Out[4]: OrderedDict([(1, 89), (2, 3), (3, 0), (4, 5)])
Never mind the way od
is printed out; it'll work as expected:
In [11]: od[1] Out[11]: 89 In [12]: od[3] Out[12]: 0 In [13]: for k, v in od.iteritems(): print k, v ....: 1 89 2 3 3 0 4 5
For Python 3 users, one needs to use the .items()
instead of .iteritems()
:
In [13]: for k, v in od.items(): print(k, v) ....: 1 89 2 3 3 0 4 5
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With