Как проверить, находится ли значение во вложенном словаре Python? - PullRequest
0 голосов
/ 11 июня 2018

Как проверить, находится ли значение во вложенном словаре Python?

Я хочу проверить, есть ли выбор, который вводит пользователь, в словаре, и если нет, добавить новый фильм в словарь, и еслиэто значит, что фильм уже сохранен.

Я бы также хотел, чтобы пользователь вводил выбор фильма и словарь для печати сведений о конкретном фильме, а не всех 10.

Нажмитепо ссылке для просмотра изображения кода.

Это письменный код:

topMovies = {1:{'Movie':'Avatar', 'Year': '2009', 'Gross Profit': '£2.788 billion', 'Budget': '£237 million'},
2:{'Movie':'Titanic', 'Year': '1997', 'Gross Profit': '£2.187 billion', 'Budget': '£200 million'},
3:{'Movie':'Star Wars: The Force Awakens', 'Year': '2015', 'Gross Profit': '£2.068 billion', 'Budget': '£306 million'},
4:{'Movie':'Avengers: Infinity War', 'Year': '2018', 'Gross Profit': '£1.814 billion', 'Budget': '£400 million'},
5:{'Movie':'Jurassic World', 'Year': '2015', 'Gross Profit': '£1.672 billion', 'Budget': '£150 million'},
6:{'Movie':'The Avengers', 'Year': '2012', 'Gross Profit': '£1.519 billion', 'Budget': '£220 million'},
7:{'Movie':'Fast and Furious 7', 'Year': '2015', 'Gross Profit': '£1.516 billion', 'Budget': '£190 million'},
8:{'Movie':'Avengers: Age of Ultron', 'Year': '2015', 'Gross Profit': '£1.405 billion', 'Budget': '£444 million'},
9:{'Movie':'Black Panther', 'Year': '2018', 'Gross Profit': '£1.344 billion', 'Budget': '£210 million'},
10:{'Movie':'Harry Potter and the Deathly Hollows: Part 2', 'Year': '2011', 'Gross Profit': '£1.342 billion', 'Budget': '£250 million (shared with part 1)'}}

for movieID, movieInfo in topMovies.items():
    print("\nNumber: ", movieID)
    for key in movieInfo:
        print(key , ": " , movieInfo[key])
print("\n")

#checking if movie already stored and if not add new movie else movie is already stored
choice = input('Please enter choice: ')
for x in topMovies:
    if choice != topMovies[x]:
        print("Enter new movie!")
        topMovies[x] = {}
        topMovies[x]['Movie'] = choice
        topMovies[x]['Year'] = input('Enter the year of release for the movie: ')
        topMovies[x]['Gross Profit'] = input('Enter the gross profit of the movie: ')
        topMovies[x]['budget'] = input('Enter the budget for the movie: ')
        print("\n")
        print(topMovies[x])
    elif choice == topMovies[x]['Movie']:
        print("Movie already stored!")
    break

Ответы [ 2 ]

0 голосов
/ 11 июня 2018

Вы должны проверить значение choice для всех фильмов 'Movie' значения до , позволяя пользователю создать новую запись:

choice = input('Please enter choice: ')
for movie in topMovies.values():
    if movie["Movie"] == choice:
        print("Movie already stored!")
        break
else:
   # IMPORTANT: this is a 'else' for the `for` loop, 
   # it will only be executed if the loop terminates 
   # without a `break`

   # create the movie here - warning: you'll need to find 
   # the highest `topMovies` key to compute the new movie key.

Обратите внимание, что это решение неэффективно(последовательное сканирование - O (N)) и не так читаемо, как могло бы быть.Вы можете улучшить его, используя лучшую структуру данных - когда вы видите диктовку, ключи которой являются последовательными восходящими целыми числами, есть вероятность, что вы вместо этого захотите list - и обратный индекс (диктовка, сопоставляющая имена фильмов с их индексами в списке).

top_movies = [
    {'Movie':'Avatar', 'Year': '2009', 'Gross Profit': '£2.788 billion', 'Budget': '£237 million'},
    {'Movie':'Titanic', 'Year': '1997', 'Gross Profit': '£2.187 billion', 'Budget': '£200 million'},
    {'Movie':'Star Wars: The Force Awakens', 'Year': '2015', 'Gross Profit': '£2.068 billion', 'Budget': '£306 million'},
    {'Movie':'Avengers: Infinity War', 'Year': '2018', 'Gross Profit': '£1.814 billion', 'Budget': '£400 million'},
    {'Movie':'Jurassic World', 'Year': '2015', 'Gross Profit': '£1.672 billion', 'Budget': '£150 million'},
    {'Movie':'The Avengers', 'Year': '2012', 'Gross Profit': '£1.519 billion', 'Budget': '£220 million'},
    {'Movie':'Fast and Furious 7', 'Year': '2015', 'Gross Profit': '£1.516 billion', 'Budget': '£190 million'},
    {'Movie':'Avengers: Age of Ultron', 'Year': '2015', 'Gross Profit': '£1.405 billion', 'Budget': '£444 million'},
    {'Movie':'Black Panther', 'Year': '2018', 'Gross Profit': '£1.344 billion', 'Budget': '£210 million'},
    {'Movie':'Harry Potter and the Deathly Hollows: Part 2', 'Year': '2011', 'Gross Profit': '£1.342 billion', 'Budget': '£250 million (shared with part 1)'}
    ]

movies_index = {movie["Movie"].lower(): index for index, movie in enumerate(top_movies)}

# ....

choice = input('Please enter choice: ').strip()
# dict lookup is O(1) and highly optimised
if choice.lower() in movies_index:
    print("Movie already stored!")
else:
    new_movie = {"Movie": choice}
    # fill in the fields
    # ...
    top_movies.append(new_movie)
    movies_index[choice.lower()] = len(top_movies) - 1
0 голосов
/ 11 июня 2018

РЕДАКТИРОВАТЬ 2: Это не работает в вашем примере.Оставить это в качестве примера «не читать всю проблему»

Если вы ищете эффективность, это сработает:

choice = input("Movie name please: ...")
if {"Movie":choice} not in topMovies.values():
    etc etc etc

РЕДАКТИРОВАТЬ: полный пример, так как выше не сделал 'т работать из коробки без подгонки под ваш код ...

topMovies={}
topMovies["1"]={"Movie":"Avatar"}
choice = input("Movie name please: ...")
if {"Movie":choice} not in topMovies.values():
    X=input("Rank: ")
    topMovies[X]={}
    topMovies[X][choice]=choice
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...