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
CodePudding user response:
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}
CodePudding user response:
it is because it reads uppercase letters as greater than lower case letters. Change the dictionary keys to .title()