简体   繁体   English

在 python 中追加字典项时需要帮助

[英]Need help in appending dictionary items in python

I am trying to get movies by genres from tmdb movie dataset by converting it into json.我正在尝试通过将 tmdb 电影数据集中的类型转换为 json 来获取电影。

There should be multiple entries for a specific genre like 'adventure', but all i get to see is the last record and seems like the previous records are getting overwritten.像“冒险”这样的特定类型应该有多个条目,但我看到的只是最后一条记录,似乎以前的记录被覆盖了。 I have verified this by adding a print statement in the if statement and the details are showing up in the console but somehow getting overwritten.我已经通过在 if 语句中添加打印语句来验证这一点,并且详细信息显示在控制台中,但不知何故被覆盖了。

Any help would be appreciated.任何帮助,将不胜感激。 Thanks!!谢谢!!

final_list = []
for i in range(1,1000):
        if genre_name in data[str(i)]['genres']:
            movie_dict["Title"] = data[str(i)]['title']
            movie_dict["Language"] = data[str(i)]['original_language']
            final_list = [movie_dict]
    return final_list

There are two obvious problems.有两个明显的问题。 You redefine final_list in the loop and you return during the first loop.您在循环中重新定义final_list并在第一个循环期间返回。

Fixing that will give you something like this:修复它会给你这样的东西:

def myfunction(data, genre_name):
    movie_dict = {}
    final_list = []
    for i in range(1,1000):
        if genre_name in data[str(i)]['genres']:
            movie_dict["Title"] = data[str(i)]['title']
            movie_dict["Language"] = data[str(i)]['original_language']
            final_list.append(movie_dict)
    return final_list

Now there is another, more subtle problem.现在还有另一个更微妙的问题。 You always add the same dictionary to the list.您总是将相同的字典添加到列表中。

To give an example:举个例子:

d = {}
l = []
for i in range(5):
    d['x'] = i ** 2
    l.append(d)
print(l)

Now l contains the same dictionary 5 times and this dictionary will have the content from the last iteration of the loop: [{'x': 16}, {'x': 16}, {'x': 16}, {'x': 16}, {'x': 16}] .现在l包含相同的字典 5 次,该字典将包含循环最后一次迭代的内容: [{'x': 16}, {'x': 16}, {'x': 16}, {'x': 16}, {'x': 16}] To fix this you have to create the dictionary in the loop, so in your code you have to move movie_dict = {} to an appropriate place:要解决此问题,您必须在循环中创建字典,因此在您的代码中,您必须将movie_dict = {}移动到适当的位置:

def myfunction(data, genre_name):
    final_list = []
    for i in range(1,1000):
        if genre_name in data[str(i)]['genres']:
            movie_dict = {}
            movie_dict["Title"] = data[str(i)]['title']
            movie_dict["Language"] = data[str(i)]['original_language']
            final_list.append(movie_dict)
    return final_list

Now some more advanced stuff.现在一些更高级的东西。 I assume data is a dictionary since you use a string for indexing.我假设data是字典,因为您使用字符串进行索引。 If you're not limited to 1000 entries but want to access all the values in the dictionary you can loop over the dictionaries values:如果您不限于 1000 个条目,但想要访问字典中的所有值,则可以遍历字典值:

def myfunction(data, genre_name):
    final_list = []

    for entry in data.values():
        if genre_name in entry['genres']:
            movie_dict = {}
            movie_dict["Title"] = entry['title']
            movie_dict["Language"] = entry['original_language']
            final_list.append(movie_dict)
    return final_list

Now let us create the dictionary on the fly in the call to append .现在让我们在调用append时动态创建字典。

def myfunction(data, genre_name):
    final_list = []

    for entry in data.values():
        if genre_name in entry['genres']:
            final_list.append({'Title': entry['title'], 'Language': entry['original_language']})
    return final_list

This can be rewritten as a list comprehension:这可以重写为列表推导:

def myfunction(data, genre_name):
    return [{'Title': entry['title'], 'Language': entry['original_language']} for entry in data.values() if genre_name in entry['genres']]

That's all.就这样。

尝试使用final_list.append(movie_dict)

Bro you were actually actually returning the list after each value was added try this way and it will not overwrite it.兄弟,您实际上是在添加每个值后返回列表尝试这种方式,它不会覆盖它。 The main reason is that you were returning the list in the for loop and everytime the loop run it save new dictionary in the list and remove the old one主要原因是您在 for 循环中返回列表,并且每次循环运行时都会在列表中保存新字典并删除旧字典

final_list = []
for i in range(1,1000):
        if genre_name in data[str(i)]['genres']:
            movie_dict["Title"] = data[str(i)]['title']
            movie_dict["Language"] = data[str(i)]['original_language']
            final_list.append(movie_dict)
return final_list

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM