I am trying to write a python code that can sort lowercase words in the order of the dictionary. Firstly sort the words by the first letter, if the first letter is the same, then compare the second letter, and so on. After sorting, print out the words in the sorted order, separated by commas. The inputed words needs to be seperated with commas aswell.Thanks in advance.
CodePudding user response:
If your dictionnary is actually a Python list containning words we can sort it directly. If it is a Python dictionnary a direct sort will sort by the keys and we need to use a lambda function to sort by the values.
words = ['yes','no','black','white']
print("# unsorted list")
print(words)
words.sort()
print("# sorted list")
print(words)
print('')
frenchWords={'yes':'oui','no':'non','black':'noire','white':'blanc'}
print("# unsorted dictionnary")
print(frenchWords)
print("# default dictionnary sort")
for i in sorted (frenchWords):
print((i, frenchWords[i]))
print("# dictionnary keys sorted")
for i in sorted (frenchWords.keys()):
print(i)
print("# dictionnary sorted by values")
print(sorted(frenchWords.items(), key = lambda kv:(kv[1], kv[0])))
output
# unsorted list
['yes', 'no', 'black', 'white']
# sorted list
['black', 'no', 'white', 'yes']
# unsorted dictionnary
{'yes': 'oui', 'no': 'non', 'black': 'noire', 'white': 'blanc'}
# default dictionnary sort
('black', 'noire')
('no', 'non')
('white', 'blanc')
('yes', 'oui')
# dictionnary keys sorted
black
no
white
yes
# dictionnary sorted by values
[('white', 'blanc'), ('black', 'noire'), ('no', 'non'), ('yes', 'oui')]
CodePudding user response:
I think there is part of this question is already answered here. but I'll post the code that should answer your question completely.
def quicksort(lst):
if not lst:
return []
return (quicksort([x for x in lst[1:] if x < lst[0]])
[lst[0]]
quicksort([x for x in lst[1:] if x >= lst[0]]))
s = "I am trying to write a python code that can sort lowercase words in the order of the dictionary"
s = s.lower().split()
print(s)
arr = s
print("Sorted array is:", quicksort(arr))
CodePudding user response:
Maybe try converting to ASCII using ord(), and then perform a stable sort such as radix sort