Почему мои python словари продолжают перезаписывать - PullRequest
0 голосов
/ 10 апреля 2020

Я пытаюсь создать словарь внутри словаря. Предполагается, что это клуб любителей mov ie, в котором вы можете добавлять фильмы в аккаунт участника, но когда я пытаюсь добавить его, он перезаписывается. Ниже приведен мой код:

import sys

movies = {}


def option_one():
    print('Club Members')
    print('=' * 12)
    for name in movies:
        print(name)
    application()


def option_two():
    name = input('Please enter the user\'s name: ')
    for movie in movies[name]:
        title = movies[name][movie]
        watch = movies[name][movie]['Watched']
        rate = movies[name][movie]['Rating']
        print('Movie', 'Rating', 'Watched', sep=' ' * 5)
        print('=' * 30)

        print(movie, movies[name][movie]['Rating'], movies[name][movie]['Watched'], sep=' ' * 8)

    application()


def option_three():
    name = input('Please enter the member\'s name: ')

    if name in movies:
        movie = input('Please enter the name of the movie: ')
        movies[name][movie]['Watched'] = movies[name][movie]['Watched'] + 1
        for movie in movies[name]:
            if movie not in movies[name][movie]:
                print('Movie not found. ')
            else:
                print('Times watched incremented. ')
    else:
        print('Sorry, member not found. ')
    application()


def option_four():
    name = input('Please enter the member\'s name: ')

    # if the name exists in movies add the movie
    if name in movies:
        # enter information and update dictionary
        movie_title = input('Enter movie name: ')
        times_watched = int(input('Enter times watched: '))
        rating = input('Enter rating: ')
        add_movie = {name: {movie_title: {'Watched': times_watched,
                                          'Rating': rating}}}
        movies.update(add_movie)
        print('Movie added')

    # if name not in movies print member not found call option 4 again
    else:
        print('Member not found')
        option_four()
    application()


def option_five():
    name = input('Enter new member name: ')
    nameDict = {name: ''}

    # update the movies dictionary with name dictionary as key
    movies.update(nameDict)
    print('Member added')
    application()


def application():
    print('=' * 33)
    print('Movie Lover\'s club')
    print('=' * 33)
    print('1. Display all club_members.')
    print('2. Display all movie information for a member.')
    print('3. Increment the times a specific movie was watched by a member.')
    print('4. Add a movie for a member.')
    print('5. Add a new member.')
    print('6. Quit')
    print('=' * 33)

    # get name input for selection
    name_selection = (input('Please enter a selection: '))

    # if statement directing name choice to corresponding method
    if name_selection == '1':
        option_one()

    if name_selection == '2':
        option_two()

    if name_selection == '3':
        option_three()

    if name_selection == '4':
        option_four()

    if name_selection == '5':
        option_five()

    if name_selection == 'Q':
        print('=' * 33)
        print('Thank you for using Movie Lover\'s Club')
        print('=' * 33)
        sys.exit()
    else:
        input('Pick a number between 1 and 5 or Q to exit program. Press enter to continue.')


application()

Приведенный выше код работает должным образом, но он не будет добавлять заголовки mov ie, только перезаписывая их. Любая помощь очень ценится.

Ответы [ 2 ]

1 голос
/ 10 апреля 2020

Edit2 : с вашим обновленным кодом, вот решение вашей проблемы. Вы действительно были очень близки, единственная проблема заключалась в том, что вы использовали .update в словаре movies, а не в словаре movies[name], так что вы каждый раз заменяли бы movies[name] на ваш новый диктовку mov ie. Решением здесь является обновление movies[name]. Кроме того, я внес изменения в вашу функцию option_five, чтобы при добавлении нового члена по умолчанию у них был пустой словарь, а не пустая строка, поэтому его можно обновить:

def option_four():
    name = input('Please enter the member\'s name: ')

    # if the name exists in movies add the movie
    if name in movies:
        # enter information and update dictionary
        movie_title = input('Enter movie name: ')
        times_watched = int(input('Enter times watched: '))
        rating = input('Enter rating: ')

        # notice how I got rid of {name: ...} and instead only used the movie
        new_movie = {movie_title: {'Watched': times_watched, 'Rating': rating}}
        # now update the user's movie dict rather than the entire movies dict
        movies[name].update(new_movie)

    # if name not in movies print member not found call option 4 again
    else:
        print('Member not found')
        option_four()
    application()

def option_five():
    name = input('Enter new member name: ')
    nameDict = {name: {}} # notice that I replaced '' with {}

    # update the movies dictionary with name dictionary as key
    movies.update(nameDict)
    print('Member added')
    application()

Сейчас Вы можете добавлять фильмы для пользователя по желанию без перезаписи

0 голосов
/ 10 апреля 2020

Причина, по которой он перезаписывается, заключается в том, что вы перезаписываете список участников каждый раз, когда хотите добавить новый mov ie. В частности, когда вы выполняете:

add_title = movies[name] = {movie_title: {'Watched': '', 'Rating': ''}}

movie[name] теперь содержит только {movie_title: {'Watched': '', 'Rating': ''}}

Вот новая версия вашего кода:

def option_four():
    name = input('Please enter the member\'s name: ')

    # enter information 
    movie_title = input('Enter movie name: ')
    times_watched = int(input('Enter times watched: '))
    rating = input('Enter rating: ')

    if name not in movies:
        movies[name] = {}

    #create the movie title value dictionary make 'movie_title input the name of dict
    movies[name][movie_title] = {'Watched': '', 'Rating': ''}

    #add watched and rating values to the movie_title dict
    movies[name][movie_title]['Watched'] = times_watched
    movies[name][movie_title]['Rating'] = rating
...