So I have a dictionary that looks like this when I print it:
{'10': -10, 'ZT21': 14, 'WX21': 12, '2': 15, '5': -3, 'UM': -25}
I want to sort these in a custom manner, which I define. Let’s say the way I want it to be sorted (by key) is ZT21, 10, WX21, UM, 5, 2.
Anyone know how to go about sorting out a dictionary in a predefined/custom manner? What I am doing is getting this dictionary from a database, and it can come out with over 20 keys, all of which have a specific order. The order is always set, but sometimes certain keys/values wouldn’t be in the dictionary. So this could happen too:
{'ZT21': 14, 'WX21': 12, '2': 15, '5': -3, 'UM': -25}
sorted (by key) is ZT21, 10, WX21, UM, 5, 2.
So the 10 isn’t there in this example, but the sorting I need is still the same, the 10 would just be absent.
Any ideas?
Updated answer for Python 3.6+
Legacy answer:
Dictionaries in Python are unordered (before Python3.6). You can get the results you need as a
listor as an OrderedDict
If you are doing a lot of these, it will be more efficient to use a
dictfor the keyorder