如何检查值是否在嵌套的python字典中?

时间:2018-06-11 11:00:56

标签: python dictionary

如何检查某个值是否在嵌套的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 :(得分:1)

在允许用户创建新条目之前,您必须针对所有电影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)),并且不具备可读性。您可以通过使用更好的数据结构来改进它 - 当您看到一个dict,其键是连续的升序整数时,您可能需要list - 而反向索引(将电影名称映射到列表中的索引的dict)

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

答案 1 :(得分:-2)

编辑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