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
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.
© 2024 OneMinuteCode. All rights reserved.