Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort dictionary by key length. Python 3.6 [duplicate]

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}

1 Answers

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}
like image 152
Austin Avatar answered Jul 20 '26 02:07

Austin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!