Как добавить новый набор пары ключ-значение в словарь в Python? - PullRequest
0 голосов
/ 18 января 2019

Я хочу разработать базовую систему управления библиотекой (lms), которая позволяет пользователю добавлять несколько книг и сохранять их в словаре, где book_name - это ключ, а список других атрибутов (author_name, publishing_name ...) - это значение для соответствующего ключа. Но после добавления первой книги, когда я добавляю вторую книгу, детали первой книги перезаписываются второй книгой, что не так, как я хочу. Использование метода update () для обновления «book_dict» также не помогло. Могу ли я получить решение этой проблемы? Вот код вместе с выводом

def addBook():
book_dict = {}
book_list = []

book_name = input("Enter the book name: ")
book_list.append(book_name)

author_name = input("Enter the author name: ")
book_list.append(author_name)

publication_name = input("Enter the publication: ")
book_list.append(publication_name)

publication_year = input("Enter the year of publication year: ")
book_list.append(publication_year)

cost = input("Enter the cost: ")
book_list.append(cost)

book_dict.update({book_name:book_list})
print(book_dict)        
return book_dict

#Ignore the display() method
'''def displayBook(books):
print('''************MENU********************
1. Add a book
2. Display a book with a particular name
3. Quit
*****************************************''')'''

choice = int(input("Enter your choice: "))

while choice != 3:
   books = {}

if choice == 1:
    books.update(addBook()) 
    print(books)

#elif choice == 2:
#   displayBook(books)

elif choice == 3:
    exit()

print('''************MENU********************
1. Add a book
2. Display a book with a particular name
3. Quit
*****************************************''')
choice = int(input("Enter your choice: "))

Выход:

************MENU********************
    1. Add a book
    2. Display a book with a particular name
    3. Quit
*****************************************
Enter your choice: 1
Enter the book name: a
Enter the author name: a
Enter the publication: a
Enter the year of publication year: 1
Enter the cost: 1
{'a': ['a', 'a', 'a', '1', '1']}
{'a': ['a', 'a', 'a', '1', '1']}
************MENU********************
    1. Add a book
    2. Display a book with a particular name
    3. Quit
*****************************************
Enter your choice: 1
Enter the book name: b
Enter the author name: b
Enter the publication: b
Enter the year of publication year: 2
Enter the cost: 2
{'b': ['b', 'b', 'b', '2', '2']}
{'b': ['b', 'b', 'b', '2', '2']}
************MENU********************
    1. Add a book
    2. Display a book with a particular name
    3. Quit
*****************************************

Ответы [ 2 ]

0 голосов
/ 18 января 2019

Добро пожаловать на ТАК, мой дорогой друг! Во-первых, вы должны сделать отступ в своем коде, во-вторых, ваша проблема в том, что вы должны установить переменную книги как глобальную. Надеюсь, этот код поможет!

def addBook(book_dict):
    book_list = []

    book_name = input("Enter the book name: ")
    book_list.append(book_name)

    author_name = input("Enter the author name: ")
    book_list.append(author_name)

    publication_name = input("Enter the publication: ")
    book_list.append(publication_name)

    publication_year = input("Enter the year of publication year: ")
    book_list.append(publication_year)

    cost = input("Enter the cost: ")
    book_list.append(cost)

    book_dict.update({book_name: book_list})
    print(book_dict)
    return book_dict


choice = int(input("Enter your choice: "))
books = {}

while choice != 3:
    if choice == 1:
        books = addBook(books)
        print(books)

    # elif choice == 2:
    #     displayBook(books)

    elif choice == 3:
        exit()

print('''************MENU********************
1. Add a book
2. Display a book with a particular name
3. Quit
*****************************************''')
choice = int(input("Enter your choice: "))
0 голосов
/ 18 января 2019

Это должно работать. Ошибка, которую я обнаружил, заключалась в том, что вы использовали неправильную структуру данных для хранения своих данных, а также вы повторно инициализировали ее при каждом вводе данных пользователем, если я правильно понял. Это обновление должно содержать больше книг и отображать их более организованно.

book_list = []

def addBook():
    book_dict = {}
    book_name = raw_input("Enter the book name: ")
    book_dict["Name"] = book_name
    author_name = raw_input("Enter the author name: ")
    book_dict["Author"] = author_name
    publication_name = raw_input("Enter the publication: ")
    book_dict["Publication"] = publication_name
    publication_year = raw_input("Enter the year of publication year: ")
    book_dict["Year"] = publication_year
    cost = raw_input("Enter the cost: ")
    book_dict["Cost"] = cost
    book_list.append(book_dict)        
    return True


def choose():
    print('''************MENU********************
    1. Add a book
    2. Display a book with a particular name
    3. Quit
    *****************************************''')
    choice = int(input("Enter your choice: "))
    if choice == 1:
        addBook() 
        print(book_list)
    #elif choice == 2:
    #   displayBook(books)
    elif choice == 3:
        exit()



while True:
    choose()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...