Reputation: 6898
I have a CSV file, and I turn this file into a dictionary using the DictReader from the CSV library.
My code is like that:
with open('file.csv', 'r') as file:
reader = csv.DictReader(file)
highest = sorted(reader, key=lambda x: (x['value']))
print(highest)
But this is don't working and the list highest
have all the data from the CSV and I only want the 10 highest values. But I don't know how to use limit the list to receive only the 10 highest values using dictionary.
I can't use Pandas
Upvotes: 1
Views: 1635
Reputation: 106598
You can slice the list after sorting to get the 10 highest values:
highest = sorted(reader, key=lambda x: x['value'])[-10:]
You can also use the heapq.nlargest
method to achieve the same in O(n log t)
(where t
is the number of items to return) time complexity instead of O(n log n):
import heapq
highest = heapq.nlargest(10, reader, key=lambda x: x['value'])
Upvotes: 4