5

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}
Sheldore
  • 37,862
  • 7
  • 57
  • 71
  • Another one [here](https://stackoverflow.com/questions/11753758/dictionary-sorting-by-key-length) – Sheldore Dec 28 '18 at 17:13
  • the key thing to note however, is that dictionaries inherently are unordered! check out OrderedDict if you specifically need it as a dictionary. – Paritosh Singh Dec 28 '18 at 17:14

3 Answers3

7

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}
Austin
  • 25,759
  • 4
  • 25
  • 48
2

Dictionaries can't be "sorted" in the traditional way because they are an unordered key-value storage. You probabilaly want to use a multidimensional list.

>>> d = [["aa", 1], ["aaaaaaa", 2], ["aaa", 3], ["a", 4]]
>>> d
[['aa', 1], ['aaaaaaa', 2], ['aaa', 3], ['a', 4]]
>>> sorted(d, key=lambda l: len(l[0]), reverse=True)
[['aaaaaaa', 2], ['aaa', 3], ['aa', 1], ['a', 4]]
vgar
  • 171
  • 6
1
dic = {"aa" : 1, "aaaaaaa": 2, "aaa" : 3, "a": 4}
new_dic={}
k = list(dic.items())
k.sort(key=lambda x:len(x[0]),reverse=True)

for i in k :
    new_dic.update({i[0]:i[1]})

print(new_dic)
sahasrara62
  • 10,069
  • 3
  • 29
  • 44