I have a python dictionary that looks like the following:
{'666 -> 999': 4388, '4000 -> 4332': 4383, '1333 -> 1665': 7998, '5666 -> 5999': 4495, '3666 -> 3999': 6267, '3000 -> 3332': 9753, '6333 -> 6665': 7966, '0 -> 332': 877}
The keys are obviously all strings, but each key depicts a range of numbers. What I'd like to do is sort this dictionary based on the first number in the key. Is there a quick method for doing so? Just using sorted on the dictionary doesn't help because the string "666" is lexically greater than the string " 1000". Thanks for any suggestions
Use a sorting key:
sorted(yourdict, key=lambda k: int(k.split()[0]))
This returns a list of keys, sorted numerically on the first part of the key (split on whitespace).
Demo:
>>> yourdict = {'666 -> 999': 4388, '4000 -> 4332': 4383, '1333 -> 1665': 7998, '5666 -> 5999': 4495, '3666 -> 3999': 6267, '3000 -> 3332': 9753, '6333 -> 6665': 7966, '0 -> 332': 877}
>>> sorted(yourdict, key=lambda k: int(k.split()[0]))
['0 -> 332', '666 -> 999', '1333 -> 1665', '3000 -> 3332', '3666 -> 3999', '4000 -> 4332', '5666 -> 5999', '6333 -> 6665']
Sorting both keys and values together:
sorted(yourdict.items(), key=lambda item: int(item[0].split()[0]))
This produces key-value pairs:
>>> sorted(yourdict.items(), key=lambda item: int(item[0].split()[0]))
[('0 -> 332', 877), ('666 -> 999', 4388), ('1333 -> 1665', 7998), ('3000 -> 3332', 9753), ('3666 -> 3999', 6267), ('4000 -> 4332', 4383), ('5666 -> 5999', 4495), ('6333 -> 6665', 7966)]
You could produce an collections.OrderedDict() object with that:
>>> from collections import OrderedDict
>>> OrderedDict(sorted(yourdict.items(), key=lambda item: int(item[0].split()[0])))
OrderedDict([('0 -> 332', 877), ('666 -> 999', 4388), ('1333 -> 1665', 7998), ('3000 -> 3332', 9753), ('3666 -> 3999', 6267), ('4000 -> 4332', 4383), ('5666 -> 5999', 4495), ('6333 -> 6665', 7966)])
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