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
If you have a dict, for example:
Dictionaries themselves do not have ordered items as such, should you want to print them etc to some order, here are some examples:
In Python 2.4 and above:
gives:
(Python below 2.4:)
Source: http://www.saltycrane.com/blog/2007/09/how-to-sort-python-dictionary-by-keys/
I think the easiest thing is to sort the dict by key and save the sorted key:value pair in a new dict.
To make it clearer:
For python3.6+, this is easily done with:
As others have mentioned, dictionaries are inherently unordered. However, if the issue is merely displaying dictionaries in an ordered fashion, you can override the
__str__
method in a dictionary subclass, and use this dictionary class rather than the builtindict
. Eg.Note, this changes nothing about how the keys are stored, the order they will come back when you iterate over them etc, just how they're displayed with
print
or at the python console.I come up with single line dict sorting.
Hope this will be helpful.