0

I am working on a program to sort a dictionary. I wrote this function:

def arrange(d):
    sorted_dict = dict(sorted(d.items()))
    return(sorted_dict)

when I run the program, it is sorted alphabetically as I would hope, except for these words: [enter image description here][1]

Any help? [1]: https://i.stack.imgur.com/A2FHn.png

Stef
  • 13,242
  • 2
  • 17
  • 28
nini78
  • 11
  • 1
    What version of Python are you using? Before Python 3.7, dictionaries aren't guaranteed to maintain their insertion order, and CPython only maintains insertion order as an implementation detail for Python 3.6+. – Brian61354270 Mar 28 '22 at 23:28
  • Looking at the screenshot, the dictionary is correctly sorted [lexicographically](https://en.wikipedia.org/wiki/Lexicographic_order). Try checking `'A' < 'a'` and `'Z' < 'a'` in your shell. – Brian61354270 Mar 28 '22 at 23:32
  • 2
    Does this answer your question? [case-insensitive list sorting, without lowercasing the result?](https://stackoverflow.com/questions/10269701/case-insensitive-list-sorting-without-lowercasing-the-result) – Brian61354270 Mar 28 '22 at 23:33

2 Answers2

0

By default, comparison of characters doesn't follow alphabetical order. It follows the order of the numbers used internally to represent the characters. A visible effect is that uppercase letters A-Z are grouped and in relative alphabetical order; lowercase letters a-z are grouped and in relative alphabetical order; but if your keys contain a mix of lowercase and uppercase letters, then the alphabet appears to be "split" in 2.

One simple way to mitigate this is to supply a custom key to sorted, and explicitly tell it to convert all characters to lowercase before comparing them.

You can convert to lowercase with str.lower() or with str.casefold().

def arrange(d):
    sorted_dict = dict(sorted(d.items(), key=lambda x: x[0].casefold()))
    return(sorted_dict)

Testing:

d = {'Battle': 0, 'Four': 1, 'above': 2, 'butter': 3}

print(arrange(d))
# {'above': 2, 'Battle': 0, 'butter': 3, 'Four': 1}
Stef
  • 13,242
  • 2
  • 17
  • 28
-2

it is because it reads uppercase letters as greater than lower case letters. Change the dictionary keys to .title()

nini78
  • 11
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Mar 29 '22 at 05:42