I want to sort my dictionary be length of keys (first- keys with the biggest length, in the end - with the smallest)
For example:
dictionary = {"aa" : 1, "aaaaaaa": 2, "aaa" : 3, "a": 4}
as a result after sorting must be:
{"aaaaaaa": 2, "aaa" : 3, "aa" : 1, "a": 4}
Dictionaries are considered unordered, but newer versions of Python (3.6+) remember the insertion order, so you can do:
d = {"aa" : 1, "aaaaaaa": 2, "aaa" : 3, "a": 4}
new_d = {}
for k in sorted(d, key=len, reverse=True):
new_d[k] = d[k]
print(new_d)
# {'aaaaaaa': 2, 'aaa': 3, 'aa': 1, 'a': 4}
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