Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ordering and filtering data from csv.dictreader

import csv

with open ('data_airbnb.csv', newline='') as f:
    reader = csv.DictReader(f, delimiter = ',')
    data_list = list(reader)

The below is 1 sample data_list content:

[OrderedDict([('room_id', '3179080'), ('survey_id', '1280'), ('host_id', '15295886'), ('room_type', 'Shared room'), ('country', ''), ('city', 'Singapore'), ('borough', ''), ('neighborhood', 'TS17'), ('reviews', '15'), ('overall_satisfaction', '5.0'), ('accommodates', '12'), ('bedrooms', '1.0'), ('bathrooms', ''), ('price', '77.0'), ('minstay', ''), ('last_modified', '2017-05-17 09:10:24.216548'), ('latitude', '1.310862'), ('longitude', '103.858828'), ('location', '0101000020E6100000E738B709F7F659403F1BB96E4AF9F43F')])

Dear friends, Im trying to retrieve the top 10 priciest room (price) with room_id and put them into a list from the data_list which contains thousands of rows. the sample list I shown was 1 row of it?

I have tried it before for a simple list but I have been receiving error accessing the values for this and do not know how to do it.

please advice. Thanks

like image 350
James Boer Avatar asked Dec 13 '25 17:12

James Boer


1 Answers

One way is to sort your list of dictionaries and select the first 10 elements. You can achieve this via sorted and a custom function:

res = sorted(data_list, key=lambda x: float(x['price']), reverse=True)[:10]

Explanation

  • lambda represents an anonymous function; you could alternatively use an explicit named function with the same logic.
  • float conversion is necessary to avoid comparing strings, which are currently used to represent prices in your OrderedDict objects.
  • reverse=True ensures we are ordering by highest price first.
  • Since sorted returns a list, you can use regular list slicing via [:10] to extract the first 10 elements.
like image 115
jpp Avatar answered Dec 15 '25 07:12

jpp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!