Sort Python List Ascending

Asked 2 years ago, Updated 2 years ago, 31 views

file = open("C:/temp/data.txt","r")

words = (word for line in file for word in line.split())

counts = dict()
for word in words:
    counts[word] = counts.get(word,0) + 1
tmp = [(k,v) for (k),(v) in counts.items()]
print(tmp)

Enter

[('it', 10), ('was', 10), ('the', 10), ('best', 1), ('of', 9), ('times', 2), ('worst', 1), ('age', 2), ('wisdom', 1), ('foolishness', 1), ('epoch', 2), ('belief', 1), ('fo', 1), ('incredulity', 1), ('season', 2), ('light', 1), ('darkness', 1), ('spring', 1), ('hope', 1), ('winter', 1), ('despair', 1)] 

``This is how it's printed

How do I sort these in ascending order?

python

2022-09-21 10:17

1 Answers

file = open("C:/temp/data.txt","r")

words = (word for line in file for word in line.split())

counts = dict()
for word in words:
    counts[word] = counts.get(word,0) + 1
tmp = sorted([(k,v) for k, v in counts.items()], key=lambda x: x[0])
print(tmp)

If you put lambdax:x[0] in the sorted function key factor, it sorts the ascending order for the first element.


2022-09-21 10:17

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.