0

I'm studying about how to work with csv files with Python (which I'm new to) and downloaded the following table, it has 89 entries with various oscar given to female actresses. I'm having problems wrapping my head around looping over key/values in dictionaries when I want specific sorting...in this case, sorting the actresses by their age.

I've tried a few solutions searching around here but couldn't understand or apply it to my code (which is very simple at the moment). What I know is that I have OrderedDict objects with a dictionary inside and it has a tuple for each key, value, e.g:

[OrderedDict([('Index', '1'), ('Year', '1928'), ('Age', '22'), ('Name', 'Janet Gaynor'), ('Movie', 'Seventh Heaven, Street Angel and Sunrise: A Song of Two Humans')]).

Current code just prints everything to console:

import csv

results = []

with open('oscar_age_female.csv') as File:
    reader = csv.DictReader(File)
    for row in reader:
        results.append(row)
    print(results)
knh190
  • 2,744
  • 1
  • 16
  • 30
mmlo95
  • 65
  • 1
  • 10

1 Answers1

0

In order to read the csv correctly you need to add in skipinitialspace otherwise the movies which contain commas in their name were being parsed out incorrectly.

import csv

results = []

with open('oscar_age_female.csv') as File:
    reader = csv.DictReader(File, skipinitialspace=True)
    for row in reader:
        results.append(row)

In order to sort the list of dictionaries by a key is then trivial once the above step is added:

print(sorted(results, key=lambda k: k['Age']))  # Youngest to oldest
print(sorted(results, key=lambda k: k['Age'], reverse=True))  # Oldest to youngest

Here is a good post on sorting lists of dicts by their keys

cullzie
  • 2,705
  • 2
  • 16
  • 21
  • Works like a charm! Thank you, I still don't know how to use those lambdas, which might explain why I was having trouble. – mmlo95 Apr 16 '19 at 00:18