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.
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to toggle on Order in ReactJS
- How to get the background from multiple images by
- PHP Recursively File Folder Scan Sorted by Modific
Will generate exactly what you want:
But this is not the write way to do this, because, It could show a distinct behavior with different dictionaries , which I have learned recently. Hence perfect way has been suggested by Tim In the response of my Query which I am sharing here.
Python dicts are un-ordered. Usually, this is not a problem since the most common use case is to do a lookup.
The simplest way to do what you want would be to create a
collections.OrderedDict
inserting the elements in sorted order.If you need to iterated, as others above have suggested, the simplest way would be to iterate over sorted keys. Examples-
Print values sorted by keys:
Get list of values sorted by keys:
Or use
pandas
,Demo:
See:
Simply:
Output: