0

So I am sorting a dictionary by having the key as the primary Genre and the value as the total number of albums in each Genre, and I cannot get the key=lambda part to output correctly, everything I have tried just outputs a blank Number of Albums.

I have tried key=lambda x:x[1] but outputs blank answers and I tried a couple other things which have not worked. Below is my code so far, the only thing as far as I am concerned is incorrect is what to put after key=lambda. I marked the part below with ** **

INPUT
import csv
def AlbumGenreAnalysis(fileName):
    myFile = open(fileName, "r")
    csvReader = csv.reader(myFile)
    header = next(csvReader)  
    genreDictionary = {}
    for row in csvReader:
        firstWord = row[4].split(",")
        if(firstWord[0] not in genreDictionary): 
            genreDictionary[firstWord[0]] = 1
        else: 
            genreDictionary[firstWord[0]] = 1
    return genreDictionary

def sortDictionaryByValues(dictionaryName, descending):
    if (type(descending) != bool and type(dictionaryName) != dict):
        raise ValueError("sortDictionaryByValues requires a dictionary and boolean as arguments, respectively")
        return None
    else:
        sortedDictionary = {}
        sortedList = sorted(dictionaryName.items(),**key=lambda ...**,reverse=descending)
        for item in sortedList:
            sortedDictionary[item[0]] = item[1]
        print("Rolling Stone Top 500 Albums Genre Analysis")
        print("Genre Name\t\tNumber Of Albums")
        for row in sortedDictionary:
            print(row+str(sortedDictionary[row]))

sortDictionaryByValues(AlbumGenreAnalysis("RollingStoneAlbumList.csv"),descending=True)

OUTPUT
Rolling Stone Top 500 Albums Genre Analysis
Genre Name      Number Of Albums
Rock1
Reggae1
Pop1
Latin1
Jazz1
Hip Hop1
Funk / Soul1
Folk1
Electronic1
Classical1
Blues1
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Zac Chan
  • 25
  • 4
  • The lambda expression does not change the items or their number, only their order. If you see a different behaviour, there might be something else wrong. – Klaus D. Apr 23 '20 at 04:30
  • 1
    Every value in your dictionary is 1, because there is no code that ever sets it to anything but 1 (hint: the contents of an `if` and its corresponding `else` will not normally be exactly identical code!). And at the end, you print out the genre and its corresponding count without any spacing in between, thus producing output like "Rock1". There is absolutely nothing you could have done with the `key=lambda` part to change any of this, you're only sorting a bunch of 1s. – jasonharper Apr 23 '20 at 04:33
  • How does the output differ from what you expect? Why do you think the answers are "blank"? – Karl Knechtel Apr 23 '20 at 04:51

0 Answers0