我有一个电影数据字典,我想创建一个新字典,其中包含预算和收入键值大于0.0的电影子集。
这是我的代码,有人可以帮忙吗?
movies_bud_rev = {}
for movie in movie_data:
if (movie_data['revenue'] != 0.0 or movie_data['budget'] != 0.0):
id = movie_data['id']
budget = movie_data['budget']
revenue = movie_data['revenue']
original_title = movie_data['original_title']
release_year = movie_data['release_year']
genre = movie_data['genre']
popularity = movie_data['popularity']
vote_average = movie_data['vote_average']
vote_count = movie_data['vote_count']
len (movies_bud_rev)
我收到的错误:
TypeError: list indices must be integers, not str
我的字典 enter image description here
我尝试创建新词典 enter image description here
答案 0 :(得分:1)
根据您提供的图片,<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="arrow"></div>
<div class="arrow active"></div>
为list of dictionaries。
因此,您需要将过滤为列表。您可以通过列表理解来实现这一目标。
movie_data
请注意一些问题:
res = [m for m in movie_data if (m['revenue'] > 0 and m['budget'] > 0)]
,而不是and
。答案 1 :(得分:0)
根据您发布的图片movie_data
是包含字典的列表
并且你在movie_data
中使用了索引,这就是你在movie
中获取错误的原因,这是字典对象
movies_bud_rev = {}
for movie in movie_data:
if (movie['revenue'] != 0.0 or movie['budget'] != 0.0):
id = movie['id']
budget = movie['budget']
revenue = movie['revenue']
original_title = movie['original_title']
release_year = movie['release_year']
genre = movie['genre']
popularity = movie['popularity']
vote_average = movie['vote_average']
vote_count = movie['vote_count']