简体   繁体   中英

Dictionary sorting issue - python

I've been working on a project for school but I've hit a small bump in the road. Almost everything is working as intended, but I am having an issue with the output in an undesired order. I want the program to sort by year as well as director if the user decides to sort by director. Theoretically I would like for the order of output to always have the earliest year first and the most recent year last. You don't need to write out the code, just aim me in the right direction! Thank you in advance!

 movieDict = {"Munich":[2005, "Steven Spielberg"],
    "The Prestige": [2006, "Christopher Nolan"],
    "The Departed": [2006, "Martin Scorsese"],
    "Into the Wild": [2007, "Sean Penn"],
    "The Dark Knight": [2008, "Christopher Nolan"],
    "Mary and Max": [2009, "Adam Elliot"],
    "The King\'s Speech": [2010, "Tom Hooper"],
    "The Artist": [2011, "Michel Hazanavicius"],
    "The Help": [2011, "Tate Taylor"],
    "Argo": [2012, "Ben Affleck"],
    "12 Years a Slave": [2013, "Steve McQueen"],
    "Birdman": [2014, "Alejandro G. Inarritu"],
    "Spotlight": [2015, "Tom McCarthy"],
    "The BFG": [2016, "Steven Spielberg"]}

askYear = True
sorted(movieDict.values())

while askYear:
    year = int(input("Enter a year between 2005 and 2016:\n"))     
    if year<2005 or year>2016:
        print("N/A")   
    else:
        for key, value in movieDict.items():
            if value[0] == year:
                print(key + ", " + str(value[1]) )
        askYear = False 

menu = "MENU" \
        "\nSort by:" \
        "\ny - Year" \
        "\nd - Director" \
        "\nt - Movie title" \
        "\nq - Quit\n"

prompt = True
firstRun = True  #this helps for spacing after 1st run through, whitespace

while prompt:
    if firstRun == True:
        print()
        firstRun = False
    print(menu)
    userChoice = input("Choose an option:\n")
    if userChoice == "q":   #quits
        prompt = False  #ends program if user quits

    elif userChoice=="y":   #sorts by year
        yearDict = {}            
        for key, value in sorted(movieDict.items(), key=lambda item: (item[1], item[0])):
            year = value[0]
            title = key
            director = value[1]
            if year not in yearDict:
                yearDict[year] = [[title, director]]
            else:
                yearDict[year].append([title, director])            
        for year in sorted(yearDict):
            print (year,end=':\n')
            movies = yearDict[year]
            for movie in sorted(movies, key = lambda x:x[0]):
                print("\t"+movie[0] + ", " + movie[1])
            print()

    elif userChoice == "d":   #sorts by director
        directorDict = {}    

        for key, value in sorted(movieDict.items(), key=lambda item: (item[1],item[1])):
            year = value[0]
            title = key
            director = value[1]
            if director not in directorDict:
                directorDict[director] = [[title, year]]
            else:
                directorDict[director].append([title, year])            
        for director in sorted(directorDict):
            print (director,end=':\n')
            movies = directorDict[director]
            for movie in sorted(movies, key = lambda x:x[0]):
                print("\t"+movie[0] + ", " + str(movie[1]))            
            print()

    elif userChoice == "t":   #sorts by title
        for key, value in sorted(movieDict.items(), key=lambda item: (item[0], item[1])):
            print(key,end=':\n')
            print("\t" + str(value[1]) + ", " + str(value[0])+"\n")
    else:
        print("Invalid input") 

From the beginning, you can transform your dictionnary in a list.

movie_list = movieDict.items()

Then, to sort it, you can use the sorted function, and use the key argument to specify what value you want to sort your array by:

movie_sorted = sorted(movie_list, key=lambda row: row[1][0]) 
# The 1 corresponds to the value of a row, and the 0 corresponds to the year.

Then if you want to sort by director, just adapt the code ;-)

Details: the key argument must be a function which takes a row and returns the value to use for sorting. lambda [argument]: [return value] is useful to create a simple function like this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM