(Python 3) Sort movies with dictionary and list

I am working on this project for school, and I cannot seem to be perfect. I got most of them, but there are two things that I struggle with. After several hours of searching the Internet and trying various workarounds, I decided that I needed to ask for help.

def main():
    movieCollectionDict = {"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\ Speech": [2010, "Tom Hooper"],
                           "The Help": [2011, "Tate Taylor"],
                           "The Artist": [2011, "Michel Hazanavicius"],
                           "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"]}
    promptForYear = True
    while promptForYear:
        yearChoice = int(input("Enter a year between 2005 and 2016:\n"))
        if yearChoice<2005 or yearChoice>2016:
            print("N/A")
        else:
            for key, value in movieCollectionDict.items():
                if value[0] == yearChoice:
                    print(key + ", " + str(value[1]) )
            promptForYear = False
    menu = "MENU" \
           "\nSort by:" \
           "\ny - Year" \
           "\nd - Director" \
           "\nt - Movie title" \
           "\nq - Quit\n"
    promptUser = True
    while promptUser:
        print("\n" + menu)
        userChoice = input("Choose an option:\n")
        if userChoice == "q":
            promptUser = False
        elif userChoice=="y":
            for key, value in sorted(movieCollectionDict.items(), key=lambda item: (item[1], item[0])):
                print (value[0],end=':\n')
                print("\t"+key + ", " + str(value[1])+"\n")
        elif userChoice == "d":
            for key, value in sorted(movieCollectionDict.items(), key=lambda key_value: key_value[1][1]):
                print(value[1],end=':\n')
                print("\t" + key + ", " + str(value[0])+"\n")
        elif userChoice == "t":
            for key, value in sorted(movieCollectionDict.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")
main()

I basically have a problem when I introduced 2006. Instead of showing both films from that year, he prints them twice. Where did I go wrong with that?

I also have a problem with extra space at the end, before the menu returns, it should have one space, but it is currently printing two empty lines.

This is the conclusion:

2005:
    Munich, Steven Spielberg

2006:
    The Prestige, Christopher Nolan

2006:
    The Departed, Martin Scorsese

2007:
    Into the Wild, Sean Penn

2008:
    The Dark Knight, Christopher Nolan

I need both films to be together since 2006 and not separate.

Here is an example of extra space:

2016:
The BFG, Steven Spielberg


MENU
Sort by:
y - Year
d - Director
t - Movie title
q - Quit

Choose an option:

Any help at all would be greatly appreciated!

+4
4

:

  • , .
  • , .
  • .

, . . , . , . , , .

def main():
    movieCollectionDict = {"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\ Speech": [2010, "Tom Hooper"],
                           "The Help": [2011, "Tate Taylor"],
                           "The Artist": [2011, "Michel Hazanavicius"],
                           "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"]}
    promptForYear = True
    while promptForYear:
        yearChoice = int(input("Enter a year between 2005 and 2016:\n"))
        if yearChoice<2005 or yearChoice>2016:
            print("N/A")   
        else:
            for key, value in movieCollectionDict.items():
                if value[0] == yearChoice:
                    print(key + ", " + str(value[1]) )
            promptForYear = False          
    menu = "MENU" \
           "\nSort by:" \
           "\ny - Year" \
           "\nd - Director" \
           "\nt - Movie title" \
           "\nq - Quit\n"
    promptUser = True
    first_time = True
    while promptUser:
        if first_time == True:
            print()
            first_time = False
        print(menu)
        userChoice = input("Choose an option:\n")
        if userChoice == "q":
            promptUser = False
        elif userChoice=="y":
            year_sorted = {}            
            for key, value in sorted(movieCollectionDict.items(), key=lambda item: (item[1], item[0])):
                year = value[0]
                title = key
                director = value[1]
                if year not in year_sorted:
                    year_sorted[year] = [[title, director]]
                else:
                    year_sorted[year].append([title, director])            
            for year in sorted(year_sorted):
                print (year,end=':\n')
                movies = year_sorted[year]
                for movie in sorted(movies, key = lambda x:x[0]):
                    print("\t"+movie[0] + ", " + movie[1])
                print()
        elif userChoice == "d":
            director_sorted = {}            
            for key, value in sorted(movieCollectionDict.items(), key=lambda item: (item[1][1])):
                year = value[0]
                title = key
                director = value[1]
                if director not in director_sorted:
                    director_sorted[director] = [[title, year]]
                else:
                    director_sorted[director].append([title, year])            
            for director in sorted(director_sorted):
                print (director,end=':\n')
                movies = director_sorted[director]
                for movie in sorted(movies, key = lambda x:x[0]):
                    print("\t"+movie[0] + ", " + str(movie[1]))            
                print()
        elif userChoice == "t":
            for key, value in sorted(movieCollectionDict.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") 

main()

:

Enter a year between 2005 and 2016:
2006
The Prestige, Christopher Nolan
The Departed, Martin Scorsese

MENU
Sort by:
y - Year
d - Director
t - Movie title
q - Quit

Choose an option:
y
2005:
    Munich, Steven Spielberg

2006:
    The Departed, Martin Scorsese
    The Prestige, Christopher Nolan

2007:
    Into the Wild, Sean Penn

2008:
    The Dark Knight, Christopher Nolan

2009:
    Mary and Max, Adam Elliot

2010:
    The King Speech, Tom Hooper

2011:
    The Artist, Michel Hazanavicius
    The Help, Tate Taylor

2012:
    Argo, Ben Affleck

2013:
    12 Years a Slave, Steve McQueen

2014:
    Birdman, Alejandro G. Inarritu

2015:
    Spotlight, Tom McCarthy

2016:
    The BFG, Steven Spielberg

MENU
Sort by:
y - Year
d - Director
t - Movie title
q - Quit

Choose an option:
+1

. if while. // prev_value. prev_value , . . , . . .

def main():
    movieCollectionDict = {"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\ Speech": [2010, "Tom Hooper"],
                           "The Help": [2011, "Tate Taylor"],
                           "The Artist": [2011, "Michel Hazanavicius"],
                           "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"]}
    promptForYear = True
    while promptForYear:
        yearChoice = int(input("Enter a year between 2005 and 2016:\n"))
        if yearChoice<2005 or yearChoice>2016:
            print("N/A")
        else:
            for key, value in movieCollectionDict.items():
                if value[0] == yearChoice:
                    print(key + ", " + str(value[1]) )
            promptForYear = False
    menu = "MENU" \
           "\nSort by:" \
           "\ny - Year" \
           "\nd - Director" \
           "\nt - Movie title" \
           "\nq - Quit\n"
    promptUser = True
    while promptUser:
        prev_val = ''
        print("\n" + menu)
        userChoice = input("Choose an option:\n")
        if userChoice == "q":
            promptUser = False
        elif userChoice=="y":
            for key, value in sorted(movieCollectionDict.items(), key=lambda item: (item[1], item[0])):
                if(prev_val!=value[0]):
                    print ("\n",value[0],end=':\n',sep='')
                    prev_val = value[0]
                print("\t"+key + ", " + str(value[1]))
        elif userChoice == "d":
            for key, value in sorted(movieCollectionDict.items(), key=lambda key_value: key_value[1][1]):
                if(prev_val!=value[1]):
                    print("\n",value[1],end=':\n',sep='')
                    prev_val = value[1]
                print("\t" + key + ", " + str(value[0]))
        elif userChoice == "t":
            for key, value in sorted(movieCollectionDict.items(), key=lambda item: (item[0], item[1])):
                if(prev_val!=key):
                    print("\n",key,end=':\n',sep='')
                    prev_val = key
                print("\t" + str(value[1]) + ", " + str(value[0]))
        else:
            print("Invalid input")
main()
+3

:

, :

a=[(2006,1),(2007,4),(2008,9),(2006,5)]

dict . - :

{2008: [9], 2006: [5], 2007: [4]}

, , , , , (2006,1) (2006,5), , . , :

{2008: [9], 2006: [1, 5], 2007: [4]}

- :

dict, :

if item[0] not in new_dict:
    new_dict[item[0]]=[item[1]]
else:
    new_dict[item[0]].append(item[1])

, , dict, :

:

a=[(2006,1),(2007,4),(2008,9),(2006,5)]

new_dict={}

for item in a:
    if item[0] not in new_dict:
        new_dict[item[0]]=[item[1]]
    else:
        new_dict[item[0]].append(item[1])

print(new_dict)

, - , :

elif userChoice=="y":
    new={}
    for key, value in sorted(movieCollectionDict.items()):
        for k in value:
            if value[0] not in new:
                new[value[0]]=[(key,value[1])]
            else:
                new[value[0]].append((key,value[1]))
    print({key: set(value) for key, value in new.items()})

, :

def main():
    movieCollectionDict = {"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\ Speech": [2010, "Tom Hooper"],
                           "The Help": [2011, "Tate Taylor"],
                           "The Artist": [2011, "Michel Hazanavicius"],
                           "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"]}
    promptForYear = True
    while promptForYear:
        yearChoice = int(input("Enter a year between 2005 and 2016:\n"))
        if yearChoice<2005 or yearChoice>2016:
            print("N/A")
        else:
            for key, value in movieCollectionDict.items():
                if value[0] == yearChoice:
                    print(key + ", " + str(value[1]) )
            promptForYear = False
    menu = "MENU" \
           "\nSort by:" \
           "\ny - Year" \
           "\nd - Director" \
           "\nt - Movie title" \
           "\nq - Quit\n"
    promptUser = True
    while promptUser:
        print("\n" + menu)
        userChoice = input("Choose an option:\n")
        if userChoice == "q":
            promptUser = False
        elif userChoice=="y":
            new={}
            for key, value in sorted(movieCollectionDict.items()):
                for k in value:
                    if value[0] not in new:
                        new[value[0]]=[(key,value[1])]
                    else:
                        new[value[0]].append((key,value[1]))
            print({key: set(value) for key, value in new.items()})

        elif userChoice == "d":
            for key, value in sorted(movieCollectionDict.items(), key=lambda key_value: key_value[1][1]):
                print(value[1],end=':\n')
                print("\t" + key + ", " + str(value[0])+"\n")
        elif userChoice == "t":
            for key, value in sorted(movieCollectionDict.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")
main()

P.S: , , , () ( ) .

+2

1

. , .

elif userChoice=="y":
    prev_years = []
    for key, value in sorted(movieCollectionDict.items(), key=lambda item: (item[1], item[0])):
        if value[0] in prev_years:
            print("\t"+key + ", " + str(value[1])+"\n")
        else:
            print (value[0],end=':\n')
            print("\t"+key + ", " + str(value[1])+"\n")
        prev_years.append(value[0])

, prev_years, , .

, 2005 prev_years. . , else !

else:
    print (value[0],end=':\n')
    print("\t"+key + ", " + str(value[1])+"\n")

,

prev_years.append(value[0])

,

prev_years = [2005]

, 2006 , , ! prev_years

,

prev_years = [2005,2006]

!

,

if value[0] in prev_years:
    print("\t"+key + ", " + str(value[1])+"\n")

, prev_years, . , !

2

,

>>> 
>>> print("hello");print("Vishnu")
hello
Vishnu
>>> print("hello"+"\n");print("Vishnu"+"\n")
hello

Vishnu

>>>

, . print() . \n, , .

:

Enter a year between 2005 and 2016:
2006
The Prestige, Christopher Nolan
The Departed, Martin Scorsese

MENU
Sort by:
y - Year
d - Director
t - Movie title
q - Quit

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

MENU
Sort by:
y - Year
d - Director
t - Movie title
q - Quit

Choose an option:
+1

Source: https://habr.com/ru/post/1687473/


All Articles